package com.decoding.twodtg.barcodereader2dtg;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

import decoding.twodtg.com.twodtgdecodelib2.BarcodeDecoderLibrary;

public class IntroActivity extends Activity
{
  private Timer timer;
  private MyTimerTask mMyTimerTask;
  private TextView txt;
  private TextView txt2;
  private TextView txt3;
  private TextView txt4;
  private Button activButton;
  private Button activManualButton;
  private BarcodeDecoderLibrary lib = new BarcodeDecoderLibrary();
  private boolean permissionsGranted = false;

  private boolean CheckPermissions()
  {
    if(android.os.Build.VERSION.SDK_INT < 23)
    {
      permissionsGranted = true;
    }else
    {
      if(ContextCompat.checkSelfPermission (this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
        return false;
      if(ContextCompat.checkSelfPermission (this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        return false;
      if(ContextCompat.checkSelfPermission (this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
        return false;
      permissionsGranted = true;
    }
    return permissionsGranted;
  }

  private void AskPermissions()
  {
    showExplanation(this,"2DTG notification.", "Our application is being initialized.\nOur license is tied to a specific device and its hardware parameters are used for this.\nWe do not use any user data!");
  }

  private void RequestPermissions()
  {
    ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
  {
    for(int i=0; i < grantResults.length; i++)
      if(grantResults[i] != 0)
        return;
    permissionsGranted = true;
    ShowLicens();
  }

  private void showExplanation(Activity act, String title, String message)
  {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title)
        .setMessage(message)
        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id)
          {
            RequestPermissions();
          }
        });
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
      @Override
      public void onCancel(DialogInterface dialog) {
        RequestPermissions();
      }
    });
    builder.create().show();
  }

  private void ShowLicens()
  {
    boolean act = lib.isActivated(this);
    if(!act)
    {
      txt2.setText("Trial - " + lib.EvaluationDayCount(this) + " days left");
      txt3.setVisibility(View.INVISIBLE);
      ((ViewGroup)(txt4.getParent())).removeView(txt4);
    }
    else
    {
      if(lib.isOneYearVersion())
      {
        int dayCount = lib.EvaluationDayCount(this);
        txt2.setText(dayCount + " days left");
        txt3.setVisibility(View.INVISIBLE);
        ((ViewGroup)(txt4.getParent())).removeView(txt4);
        if(dayCount > 0)
        {
          ((ViewGroup) (activButton.getParent())).removeView(activButton);
          ((ViewGroup) (activManualButton.getParent())).removeView(activManualButton);
        }
      }else
      {
        ((ViewGroup) (activButton.getParent())).removeView(activButton);
        ((ViewGroup) (activManualButton.getParent())).removeView(activManualButton);
      }
    }
    if(lib.isOneYearVersion())
      txt.setText(txt.getText() + "\n(1 year License)");

    if(act) // temporary. Work on sites
    {
      txt2.setText("");
      txt3.setText("");
      txt4.setText("");
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_intro);

    txt = (TextView) this.findViewById(R.id.textView);
    txt2 = (TextView) this.findViewById(R.id.textView2);
    txt3 = (TextView) this.findViewById(R.id.textView3);
    txt4 = (TextView) this.findViewById(R.id.textView4);
    activButton = (Button) this.findViewById(R.id.buttonActivationOnline);
    activManualButton = (Button) this.findViewById(R.id.buttonActivationManual);

    if(!CheckPermissions())
    {
      // No access rights yet
      txt2.setText("Access rights necessary for work are not provided!");
      txt3.setText("");
      txt4.setText("");

      AskPermissions();
     }else
    {
      ShowLicens();
    }

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    if(size.y  < 700)
    {
      try
      {
        ImageView logo = (ImageView) this.findViewById(R.id.imageView);
        ((ViewManager) logo.getParent()).removeView(logo);
      }catch(Exception e)
      {}
    }

  }

  static public String SiteUrl = "http://2dtg.com/products/mobile-barcode-decoding/mobile-barcode-decoder-android";

  public void UrlClick(View v)
  {
    CloseTimer();
    if(lib.isIndastrialVersion() && !lib.isActivated(this))
    {
      ActivationActivity.ToOnlineActivation(this);
    }
    else
    {
      Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(SiteUrl));
      startActivity(browserIntent);
    }
  }

  public void ActivationOnlineClick(View v)
  {
    if(!permissionsGranted) return;
    CloseTimer();
    ActivationActivity.ToOnlineActivation(this);
  }

  public void ActivationManualClick(View v)
  {
    if(!permissionsGranted) return;
    CloseTimer();
    ActivationManualActivity.Create(this);
  }

  public void Click(View v)
  {
    if(!permissionsGranted) return;
    if(lib.isActivated(this) || (lib.EvaluationDayCount(this) > 0))
    {
      MainActivity.Create(this);
    }
  }

  @Override
  protected void onResume()
  {
    super.onResume();
    timer = new Timer();
    mMyTimerTask = new MyTimerTask();
    timer.schedule(mMyTimerTask, 5000);
  }

  @Override
  protected void onPause()
  {
    super.onPause();
    CloseTimer();
  }

  private void CloseTimer()
  {
    if (timer != null)
    {
      timer.cancel();
      timer.purge();
      timer = null;
    }
  }

  class MyTimerTask extends TimerTask
  {
    @Override
    public void run()
    {
      if(permissionsGranted)
        runOnUiThread(new Runnable()
      {
        @Override
        public void run()
        {
          Click(null);
        }
      });
    }
  }
}
