#!/usr/bin/perl

use strict;

my $SRC='/Users/robert.lill/workspace/alfred/personalization-manager/src/main/java/eu/alfred/personalization_manager/webservices/PersonalizationManagerService.java';
my $TRG='/Users/robert.lill/workspace/alfred/mobileassistantfoundation/personalizationmanagerapi/src/main/java/alfred/eu/personalizationmanagerapi';
my $PAS='/Users/robert.lill/workspace/alfred/mobileassistantfoundation/PersonalAssistantService/src/main/java/eu/alfred/personalassistant/service/personalization';
my $SHR='/Users/robert.lill/workspace/alfred/personalassistantcommons/PersonalAssistantShared/src/main/java/eu/alfred/api/personalization';

my @calls;

my ($path,$method,$description,$response,$name,$args);

my $locmap = {'RequestBody' => 'Field', 'PathVariable' => 'Path'};


sub camelCaseToCapitals($)
{
  my $s = shift;
  my $res = '';
  for my $p (split /([A-Z])/, $s)
  {
    if ($p =~ /[A-Z]/)
    {
      $res .= "_$p";
    }
    else
    {
      $res .= uc($p);
    }
  }
  return $res;
}

open IN, "< $SRC";
my $line;
while ($line = <IN>)
{
  chomp $line;

  if ($line =~ /RequestMapping\s*\(\s*value\s*=\s*"(.*?)"/)
  {
    $path = $1;
  }

  if ($line =~ /method\s*=\s*RequestMethod.(\w+)/)
  {
    $method = $1;
  }

  if ($line =~ /ApiOperation\s*\(\s*value\s*=\s*"(.*?)"/)
  {
    $description = $1;
  }

  if ($line =~ /public\s+ResponseEntity<(List<\w+>|\w+)> (\w+)\((.*)\)/)
  {
    $response = $1;
    $name = $2;
    my @arglist;
    for my $arg (split /,/, $3)
    {
      $arg =~ /@(\w+)\s+(\w+)\s+(\w+)/;
      my $loc = $locmap->{$1};
      push @arglist, {'location' => $loc, 'type' => $2, 'name' => $3};
    }
    $args = \@arglist;
    push @calls, {'path' => $path, 'method' => $method, 'description' => $description, 'name' => $name, 'response' => $response, 'args' => $args};
  }
}

close IN;


sub PMservice()
{

open OUT, "> $TRG/PersonalizationManagerService.java";

print OUT << "EOT";
package alfred.eu.personalizationmanagerapi;

import alfred.eu.personalizationmanagerapi.client.dto.Contact;
import alfred.eu.personalizationmanagerapi.client.dto.Group;
import alfred.eu.personalizationmanagerapi.client.dto.HealthProfile;
import alfred.eu.personalizationmanagerapi.client.dto.Requesters;
import alfred.eu.personalizationmanagerapi.client.dto.UserProfile;
import retrofit.client.Response;
import retrofit.http.DELETE;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
import retrofit.http.Field;

public interface PersonalizationManagerService {

EOT

for my $rref (@calls)
{
  my $bodyarg = 0;
  my @arglist;
  for my $arg (@{$rref->{'args'}})
  {
    $bodyarg = 1 if ($arg->{'location'} eq 'Field');
    push @arglist, "\@" . $arg->{'location'} . '("' . $arg->{'name'} . '") ' . $arg->{'type'} . ' ' . $arg->{'name'};
  }

  print OUT "	// " . $rref->{'description'} . "\n";
  print OUT "	\@FormUrlEncoded\n" if ($bodyarg == 1);
  print OUT "	\@" . $rref->{'method'} . '("' . $rref->{'path'} . "\")\n";
  $args = join ", ", @arglist;
  print OUT "	public Response " . $rref->{'name'} . "($args);\n";
  print OUT "\n";
}

print OUT "}\n";
close OUT;

}

sub PMgr()
{

open OUT, "> $SHR/webservice/PersonalizationManager.java";

print OUT << "EOT";
package eu.alfred.api.personalization.webservice;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import eu.alfred.api.personalization.model.*;
import eu.alfred.api.personalization.responses.PersonalizationResponse;
import eu.alfred.api.personalization.client.*;


public class PersonalizationManager {

    private Messenger messenger;

    private class PersonalizationSuccessResponse extends Handler {
        private PersonalizationResponse personalizationSuccessResponse;

        public PersonalizationSuccessResponse(PersonalizationResponse personalizationSuccessResponse) {
            this.personalizationSuccessResponse = personalizationSuccessResponse;
        }

        \@Override
        public void handleMessage(Message msg) {
            int respCode = msg.what;

            switch (respCode) {
                case PersonalizationConstants.CREATE_USER_PROFILE_RESPONSE:
                case PersonalizationConstants.UPDATE_USER_PROFILE_RESPONSE:
                case PersonalizationConstants.DELETE_USER_PROFILE_RESPONSE:
                case PersonalizationConstants.CREATE_USER_CONTACT_RESPONSE:
                case PersonalizationConstants.UPDATE_USER_CONTACT_RESPONSE:
                case PersonalizationConstants.DELETE_USER_CONTACT_RESPONSE:
                case PersonalizationConstants.CREATE_REQUESTER_RESPONSE:
                case PersonalizationConstants.UPDATE_REQUESTER_RESPONSE:
                case PersonalizationConstants.DELETE_REQUESTER_RESPONSE:
                case PersonalizationConstants.ADD_MEMBER_TO_GROUP_RESPONSE:
                case PersonalizationConstants.CREATE_GROUP_RESPONSE:
                case PersonalizationConstants.DELETE_GROUP_RESPONSE:
                case PersonalizationConstants.DELETE_USER_HEALTH_PROFILE_RESPONSE:
                case PersonalizationConstants.UPDATE_GROUP_RESPONSE:
                case PersonalizationConstants.UPDATE_USER_HEALTH_PROFILE_RESPONSE:
                case PersonalizationConstants.CREATE_USER_HEALTH_PROFILE_RESPONSE:
                case PersonalizationConstants.REMOVE_MEMBER_FROM_GROUP_RESPONSE:


                    JSONObject jsonResponse = null;

                    try {
                        jsonResponse = new JSONObject(msg.getData().getString("JsonData", "{}"));
                        personalizationSuccessResponse.OnSuccess(jsonResponse);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        personalizationSuccessResponse.OnError(e);
                    }
                    break;
            }
        }
    }

    private class PersonalizationDataResponse extends Handler {
        private PersonalizationResponse personalizationDataResponse;

        public PersonalizationDataResponse(PersonalizationResponse personalizationDataResponse) {
            this.personalizationDataResponse = personalizationDataResponse;
        }

        \@Override
        public void handleMessage(Message msg) {
            int respCode = msg.what;

            switch (respCode) {
                case PersonalizationConstants.CREATE_USER_PROFILE_FILTER_RESPONSE:
                case PersonalizationConstants.CREATE_USER_PROFILE_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_CONTACTS_BY_CRITERIA_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_PROFILES_LAST_SYNC_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_PROFILE_RESPONSE:
                case PersonalizationConstants.UPDATE_REQUESTER_RESPONSE:
                case PersonalizationConstants.UPDATE_USER_CONTACT_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_PROFILES_BY_CRITERIA_RESPONSE:
                case PersonalizationConstants.RETRIEVE_REQUESTER_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_REQUESTER_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_CONTACTS_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_ID_RESPONSE:
                case PersonalizationConstants.GET_UNSYNCHRONIZED_USER_PROFILES_RESPONSE:
                case PersonalizationConstants.RETRIEVE_ALL_USER_CONTACTS_RESPONSE:
                case PersonalizationConstants.RETRIEVE_GROUP_RESPONSE:
                case PersonalizationConstants.RETRIEVE_GROUPS_WITH_MEMBER_RESPONSE:
                case PersonalizationConstants.RETRIEVE_FILTERED_GROUPS_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_CONTACT_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_HEALTH_PROFILE_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_PROFILE_SENSORED_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USER_PROFILES_RESPONSE:
                case PersonalizationConstants.RETRIEVE_USERS_GROUPS_RESPONSE:
                case PersonalizationConstants.UPDATE_GROUP_RESPONSE:

                    JSONArray jsonResponse = null;

                    try {
                        jsonResponse = new JSONArray(msg.getData().getString("response"));
                        personalizationDataResponse.OnSuccess(jsonResponse);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        personalizationDataResponse.OnError(e);
                    }
                    break;
            }
        }
    }

    public PersonalizationManager(Messenger messenger) {
        this.messenger = messenger;
    }

EOT

for my $rref (@calls)
{
  my $bodyarg = 0;
  my @arglist;
  for my $arg (@{$rref->{'args'}})
  {
    $bodyarg = 1 if ($arg->{'location'} eq 'Field');
    push @arglist, $arg->{'type'} . ' ' . $arg->{'name'};
  }

  print OUT "\n\t// " . $rref->{'description'} . "\n";
  $args = join ", ", @arglist;

  my $name = $rref->{'name'};
  my $nameUC = &camelCaseToCapitals($name);
  my $restype = ($name =~ /^(get|retrieve)/) ? "Data" : "Success";

  print OUT << "EOT";
    public void ${name}(${args}, PersonalizationResponse response) {
        if (messenger != null) {
            Message msg = Message.obtain(null, PersonalizationConstants.${nameUC});

            if (response != null)
                msg.replyTo = new Messenger(new Personalization${restype}Response(response));

            Bundle data = new Bundle();

EOT

  my $useGson = 0;
  for my $arg (@{$rref->{'args'}})
  {
    my $at = $arg->{'type'};
    $useGson = 1 unless ($at eq 'String');
  }

  print OUT "\t\t\tGson gson = new Gson();\n" if $useGson == 1;

  for my $arg (@{$rref->{'args'}})
  {
    my $an = $arg->{'name'};
    my $at = $arg->{'type'};
    if ($at eq 'String')
    {
      print OUT "\t\t\tdata.putString(\"$an\", ${an});\n";
    }
    else
    {
      print OUT "\t\t\t${at}Dto ${an}Dto = ${at}Mapper.toDto($an);\n";
      print OUT "\t\t\tString ${an}Json = gson.toJson(${an}Dto);\n";
      print OUT "\t\t\tdata.putString(\"$an\", ${an}Json);\n";
    }
  }

  print OUT << "EOT";
            msg.setData(data);
            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
EOT

}

print OUT "}\n";
close OUT;

}


sub tfac()
{

open OUT, "> $PAS/PersonalizationCRUDTaskFactory.java";

print OUT << "EOT";
package eu.alfred.personalassistant.service.personalization;

import android.content.Context;
import android.os.AsyncTask;

import eu.alfred.api.personalization.webservice.PersonalizationConstants;
import eu.alfred.personalassistant.service.personalization.tasks.CreateUserProfileTask;
import eu.alfred.personalassistant.service.personalization.tasks.RetrieveUserProfileTask;

public class PersonalizationCRUDTaskFactory {
    public static AsyncTask<PersonalizationMessageClass, Void, String> GetInstance(Context context, int msgType){
        switch(msgType){
EOT

for my $rref (@calls)
{
  my $name = $rref->{'name'};
  my $nameuc = ucfirst($name);
  my $nameUC = &camelCaseToCapitals($name);

  print OUT "\t\t\t// " . $rref->{'description'} . "\n";
  print OUT "\t\t\tcase PersonalizationConstants.${nameUC}:\n";
  print OUT "\t\t\t\treturn new ${nameuc}Task(context);\n";

}

print OUT << "EOT";
            default:
                throw new IllegalArgumentException("The parameter value is invalid. Value: " + String.valueOf(msgType));
        }
    }
}
EOT
close OUT;

}



sub client()
{


for my $rref (@calls)
{
  my $name = $rref->{'name'};
  my $nameuc = ucfirst($name);
  my $response = $rref->{'response'};

#  next if $name ne 'createUserProfile';

# -------------------- Client -----------------------------

  my $requestparams = '';
  my @arglist;
  for my $par (@{$rref->{'args'}})
  {
    my $pn = $par->{'name'};
    my $pt = $par->{'type'};

    if ($pt eq 'String' && $pn =~ /id$/i)
    {
      $requestparams .= "\t\t$pt $pn = request.$pn;\n";
    }
    elsif ($pt eq 'String' && $par->{'location'} eq 'Field' && $pn eq 'valuesToUpdate')
    {
      $requestparams .= "\t\t$pt $pn = request.valuesToUpdate;\n";
    }
    else
    {
      $requestparams .= "\t\t$pt $pn = new ${pt}Mapper().toModel(request.${pn});\n";
    }
    push @arglist, $pn;
  }
  my $requestarglist = join ', ', @arglist;
  
  my $responsetype = "${nameuc}Response";
  if ($response eq 'String')
  {
    $responsetype = "StringResponse";
  }
  elsif ($response eq 'List<UserProfile>')
  {
    $responsetype = "UserProfileResponse";
  }
  elsif ($response eq 'List<HealthProfile>')
  {
    $responsetype = "HealthProfileResponse";
  }
  elsif ($response eq 'List<Group>')
  {
    $responsetype = "GroupResponse";
  }
  elsif ($response eq 'List<Contact>')
  {
    $responsetype = "ContactResponse";
  }
  elsif ($response eq 'List<Requester>')
  {
    $responsetype = "RequesterResponse";
  }



  open OUT, "> $TRG/client/client/${nameuc}Client.java";

  print OUT << "EOT";
package alfred.eu.personalizationmanagerapi.client.client;

import android.content.Context;

import alfred.eu.personalizationmanagerapi.PersonalizationManagerAdapter;
import alfred.eu.personalizationmanagerapi.PersonalizationManagerService;
import alfred.eu.personalizationmanagerapi.client.ClientResponse;
import alfred.eu.personalizationmanagerapi.client.dto.*;
import alfred.eu.personalizationmanagerapi.client.mapper.StringResponseMapper;
import alfred.eu.personalizationmanagerapi.client.mapper.UserProfileMapper;
import alfred.eu.personalizationmanagerapi.client.request.${nameuc}Request;
import alfred.eu.personalizationmanagerapi.client.response.${responsetype};
import alfred.eu.personalizationmanagerapi.util.Strings;

import retrofit.client.Response;


public class ${nameuc}Client extends Client<${nameuc}Request, ClientResponse<${responsetype}>> {

	public ${nameuc}Client(Context context) {
		super(context);
	}

	\@Override
	protected ClientResponse<${responsetype}> request(${nameuc}Request request) throws Exception {
		PersonalizationManagerService service = PersonalizationManagerAdapter.getInstance(getContext()).getService();

${requestparams}

		Response serviceResponse = service.${name}(${requestarglist});

		printResponse(serviceResponse);

EOT

  if ($response eq 'String')
  {
    print OUT << "EOT";
		ClientResponse<StringResponse> response = new StringResponseMapper().mapResponse(
				Strings.convertStreamToString(serviceResponse.getBody().in(), "UTF-8"));
EOT
  }
  else
  {
    print OUT << "EOT";
		ClientResponse<${response}> response = new ${responsetype}Mapper().mapResponse(
				Strings.convertStreamToString(serviceResponse.getBody().in(), "UTF-8"));
EOT
  }
    print OUT << "EOT";

		if ("OK".equals(response.status)) {
			return response;
		} else {
			throw new Exception("${nameuc} failed");
		}
	}
}
EOT
  close OUT;

 }

}


sub task()
{

for my $rref (@calls)
{
  my $name = $rref->{'name'};
  my $nameuc = ucfirst($name);
  my $response = $rref->{'response'};
  my $nameUC = &camelCaseToCapitals($name);

#  next if $name ne 'createUserProfile';
#  next if $name ne 'createUserContact';

# -------------------- Task -----------------------------

  my $requestparams = '';
  my @arglist;
  for my $par (@{$rref->{'args'}})
  {
    if ($par->{'type'} eq 'String' && $par->{'name'} =~ /id$/i)
    {
      $requestparams .= "\t\t" . $par->{'type'} . " " . $par->{'name'} . " = request." . $par->{'name'} . ";\n";
    }
    elsif ($par->{'type'} eq 'String' && $par->{'location'} eq 'Field' && $par->{'name'} eq 'valuesToUpdate')
    {
      $requestparams .= "\t\t" . $par->{'type'} . " " . $par->{'name'} . " = request.valuesToUpdate;\n";
    }
    else
    {
      $requestparams .= "\t\t" . $par->{'type'} . " " . $par->{'name'} . " = new " . $par->{'type'} . "RequestMapper().toModel(request);\n";
    }
    push @arglist, $par->{'name'};
  }
  my $requestarglist = join ', ', @arglist;
  
  my $responsetype = "${nameuc}Response";
  if ($response eq 'String')
  {
    $responsetype = "StringResponse";
  }
  elsif ($response eq 'List<UserProfile>')
  {
    $responsetype = "UserProfilesResponse";
  }
  elsif ($response eq 'List<HealthProfile>')
  {
    $responsetype = "HealthProfilesResponse";
  }
  elsif ($response eq 'List<Group>')
  {
    $responsetype = "GroupsResponse";
  }
  elsif ($response eq 'List<Contact>')
  {
    $responsetype = "ContactsResponse";
  }
  elsif ($response eq 'List<Requester>')
  {
    $responsetype = "RequestersResponse";
  }



  open OUT, "> $PAS/tasks/${nameuc}Task.java";

  print OUT << "EOT";
package eu.alfred.personalassistant.service.personalization.tasks;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.google.gson.Gson;

import alfred.eu.personalizationmanagerapi.client.ClientResponse;
import alfred.eu.personalizationmanagerapi.client.client.${nameuc}Client;
import alfred.eu.personalizationmanagerapi.client.request.${nameuc}Request;
import alfred.eu.personalizationmanagerapi.client.response.${responsetype};
EOT

  for my $par (@{$rref->{'args'}})
  {
    my $pt = $par->{'type'};
    if ($pt ne 'String')
    {
      print OUT "import eu.alfred.api.personalization.client.${pt}Dto;\n";
      print OUT "import alfred.eu.personalizationmanagerapi.client.mapper.${pt}ResponseMapper;\n";
    }
  }
 

print OUT << "EOT";
import eu.alfred.api.personalization.webservice.PersonalizationConstants;
import eu.alfred.personalassistant.service.personalization.PersonalizationMessageClass;

public class ${nameuc}Task extends AsyncTask<PersonalizationMessageClass, Void, String> {

    private final static String TAG = "${nameuc}Task";

    private Context context;
    private PersonalizationMessageClass msg;
    private Exception exception;

    public ${nameuc}Task(Context context) {
        this.context = context;
    }

    \@Override
    protected String doInBackground(PersonalizationMessageClass... params) {
        try {
            msg = params[0];
            ${nameuc}Request request = new ${nameuc}Request();
EOT
  for my $par (@{$rref->{'args'}})
  {
    my $pn = $par->{'name'};
    my $pt = $par->{'type'};
    if ($pt eq 'String')
    {
      print OUT "\t\t\trequest.$pn = msg.data.getString(\"$pn\");\n";
    }
    else
    {
      print OUT "\t\t\trequest.$pn = new Gson().fromJson(msg.data.getString(\"$pn\"), ${pt}Dto.class);\n";
    }
  }
  print OUT << "EOT";

            ${nameuc}Client client = new ${nameuc}Client(context);
            ClientResponse<${responsetype}> response = client.execute(request);

            if (response.errorCode != 0)
                exception = new Exception("(" + response.errorCode + ") " + response.status);

EOT

  if ($response eq 'String')
  {
    print OUT "\t\t\tString result = response.data.string;\n";
  }
  else
  {
    print OUT "\t\t\tString result = new ${responsetype}Mapper().toModel(response.data);\n";
  }


  print OUT << "EOT";
            return new Gson().toJson(result);
        } catch (Exception e) {
            exception = e;
            Log.e(TAG, e.getClass().getSimpleName(), e);
        }
        return null;
    }

    \@Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Message resp = Message.obtain(null, PersonalizationConstants.${nameUC}_RESPONSE);
        Bundle bundle = new Bundle();
        bundle.putString(PersonalizationConstants.EXTRAS_JSON, result);
        if (exception != null)
            bundle.putString(PersonalizationConstants.EXTRAS_EXCEPTION, exception.getClass().getSimpleName() + ": " + exception.getMessage());

        resp.setData(bundle);
        try {
            msg.replyTo.send(resp);
        } catch (RemoteException e) {
            Log.e(TAG, e.getClass().getSimpleName(), e);
        }
    }
}
EOT
  close OUT;

 }

}


sub request()
{

for my $rref (@calls)
{
  my $name = $rref->{'name'};
  my $nameuc = ucfirst($name);
  my $response = $rref->{'response'};
  my $nameUC = &camelCaseToCapitals($name);


# -------------------- Request -----------------------------

  open OUT, "> $TRG/client/request/${nameuc}Request.java";

  print OUT << "EOT";
package alfred.eu.personalizationmanagerapi.client.request;

import com.google.gson.annotations.Expose;

public class ${nameuc}Request {
EOT

  for my $par (@{$rref->{'args'}})
  {
    print OUT "\t\@Expose\n";
    print OUT "\tpublic " . $par->{'type'} . " " . $par->{'name'} . ";\n";
  }

  print OUT "}\n";

  close OUT;

 }

}


sub response()
{

for my $rref (@calls)
{
  my $name = $rref->{'name'};
  my $nameuc = ucfirst($name);
  my $response = $rref->{'response'};
  my $nameUC = &camelCaseToCapitals($name);



# -------------------- Response -----------------------------

  my $resobj = $name;
  $resobj =~ s/^[a-z]*([A-Z])//;
  $resobj = lc($1) . $resobj;

  open OUT, "> $TRG/client/response/${nameuc}Response.java";

  print OUT << "EOT";
package alfred.eu.personalizationmanagerapi.client.response;

import com.google.gson.annotations.Expose;

public class ${nameuc}Response {

	\@Expose
	public ${response} ${resobj};
}
EOT

  close OUT;

}

}

print "apigenerator [PMservice/PMgr/client/task/request/response]\n";

for my $t (@ARGV)
{
  &PMservice() if $t eq 'PMservice';
  &PMgr() if $t eq 'PMgr';
  &tfac() if $t eq 'tfac';
  &client() if $t eq 'client';
  &task() if $t eq 'task';
  &request() if $t eq 'request';
  &response() if $t eq 'response';
}


