package jp.odakyu.toiletsignage.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.graphics.Typeface;
import android.widget.Toast;
import jp.odakyu.toiletsignage.R;
import jp.odakyu.toiletsignage.info.ToiletInfo;
import jp.odakyu.toiletsignage.logic.MainLogic;
import jp.odakyu.toiletsignage.application.ToiletApplication;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class MainActivity extends ParentActivity {
    private final String TAG = "MainActivity";

    private TextView mMessageTextView;
    private final int REQUEST_PERMISSION = 1000;
    private final int REQUEST_CODE = 1;

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

        mMessageTextView = findViewById(R.id.fullscreen_content);
        mMessageTextView.setTypeface(Typeface.createFromAsset(getAssets(), "meiryob.ttf"));

        if (!toiletInfo.getUsbFileCopyComplete()) {
            //外部ストレージの権限付与
            if (checkPermission()) {
                //USBからJSONデータ取得
                getUsbFileInfo();
            } else {
                requestLocationPermission();
            }
        }
    }

    private void getUsbFileInfo() {

        MainLogic mainLogic = new MainLogic();

        try {
            mainLogic.getToiletDefaultInfo(this);
            if (!toiletInfo.getValidation()) {
                mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_DEFAULT_TOILET_VALIDATION_FAIL));
                Log.e(TAG, "ToiletDefaultJson validation fail");
                return;
            }
            if (toiletInfo.getToiletDefaultJsonArray() == null && toiletInfo.getToiletDefaultJsonArray().size() == 0) {
                mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_DEFAULT_TOILET_NULL));
                Log.e(TAG, "ToiletDefaultArray NULL");
                return;
            }
            toiletInfo.setUsbFileCopyComplete(TRUE);
            ToiletApplication application = (ToiletApplication)this.getApplication();
            application.startTimer();

        } catch (Exception e) {
            mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_DEFAULT_TOILET_NULL));
            String stackTrace = Log.getStackTraceString(e);
            Log.e(TAG, stackTrace);
            e.printStackTrace();
        }
    }

    // permissionの確認
    public boolean checkPermission() {
        // 既に許可している
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_GRANTED){
            return TRUE;
        }
        return  FALSE;
    }

    // 許可を求める
    private void requestLocationPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION);

        } else {
            Toast toast =
                    Toast.makeText(getApplicationContext(), "アプリ実行に許可が必要です", Toast.LENGTH_SHORT);
            toast.show();
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_PERMISSION);
        }
    }

    // 結果の受け取り
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            // 使用が許可された
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getUsbFileInfo();
            } else {
                // それでも拒否された時の対応
                Toast toast =
                        Toast.makeText(this, "許可しないと、正常に動作できないので、アプリを再起動してださい。", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }

    @Override
    protected void onResume() {
        Log.i(TAG, "onResume");
        super.onResume();
    }
    @Override
    protected void onPause() {
        Log.i(TAG, "onPause");
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        Log.i(TAG, "onStop");
        super.onStop();
    }

    @Override
    protected void onStart() {
        Log.i(TAG, "onStart");
        super.onStart();
    }

    @Override
    public void reloadDisplayView() {
        Log.d(TAG, "reloadDisplayView");
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (toiletInfo.getConnectErrorCount() == 0) {
                    if (toiletInfo.getToiletDefaultJsonArray().size() > 0 && toiletInfo.getResultToiletJsonMapSize() > 0) {
                        //Move Signage View
                        Intent intent = new Intent(MainActivity.this, SignageActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_TOILET_SERVER_CONNECT_FAIL));
                    }
                } else {
                    if (toiletInfo.getNetworkConnect()) {
                        mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_NETWORK_DIS_CONNECT));
                    } else {
                        mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_TOILET_SERVER_CONNECT_FAIL));
                    }
                }
            }
        });
    }
}
