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.widget.TextView;
import android.graphics.Typeface;
import android.widget.Toast;
import jp.odakyu.toiletsignage.R;
import jp.odakyu.toiletsignage.constants.ToiletConstants;
import jp.odakyu.toiletsignage.info.ToiletInfo;
import jp.odakyu.toiletsignage.log.Logger;
import jp.odakyu.toiletsignage.logic.MainLogic;
import jp.odakyu.toiletsignage.application.ToiletApplication;

/**
 * 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;

    @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() {
        try {
            int result = MainLogic.getToiletDefaultInfo(getApplicationContext());
            if (result == ToiletConstants.VALUE_GET_USB_INFO_VALIDATION_FAIL) {
                mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_DEFAULT_TOILET_VALIDATION_FAIL));
                Logger.w(TAG, "USBToiletDefaultJson validation fail");
                return;
            }
            if (result == ToiletConstants.VALUE_GET_USB_INFO_FAIL) {
                mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_DEFAULT_TOILET_NULL));
                Logger.w(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));
            Logger.e(TAG, e.getLocalizedMessage(), e);
        }
    }

    // permissionの確認
    private 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 reloadDisplayView(final int errorCount, final boolean isNetworkConnect) {
        Logger.d(TAG, "reloadDisplayView");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (errorCount == 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 (isNetworkConnect) {
                        mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_TOILET_SERVER_CONNECT_FAIL));
                    } else {
                        mMessageTextView.setText(getString(R.string.initDisplayStringError, ToiletInfo.VALUE_NETWORK_DIS_CONNECT));
                    }
                }
            }
        });
    }
}
