package com.dinect.checker;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.Toast;
import com.dinect.checker.zbar.CameraActivity;
import com.dinect.checker.zxing.ScannerActivity;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.GeneratedPluginRegistrant;

import java.util.*;

public class MainActivity extends FlutterActivity {

    private static final int START_SCANNER_REQUEST_CODE = 2017;
    private static final String FLUTTER_CHANNEL_NAME = "com.dinect.checker/instance_id";

    static final String PREF_API_URL = "prefs_api_token";
    static final String PREF_APP_TOKEN = "pres_app_token";
    static final String PREF_POS_TOKEN = "pref_pos_token";
    static final String PREF_APP_BAR_COLOR = "pref_app_bar_color";
    static final String SCANNER_BACKEND_KEY = "scanner_backend_idx";

    static final int ZXING = 0;
    static final int ZBAR = 1;

    static final Class[] SCANNER_BACKEND = {
            ScannerActivity.class,
            CameraActivity.class,
    };

    private MethodChannel mChannel;
    private Map mScannerArgs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);
        mChannel = new MethodChannel(getFlutterView(), FLUTTER_CHANNEL_NAME);
        mChannel.setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall call, Result result) {
                        callMethod(call, result);
                    }
                });
    }

    private void callMethod(MethodCall call, Result result) {
        switch (call.method) {
            case "getLocale":
                result.success(getLanguage());
                break;
            case "getFlavor":
                result.success(BuildConfig.flavor);
                break;
            case "getCurrency":
                result.success(BuildConfig.currency);
                break;
            case "startScanner":
                mScannerArgs = call.arguments();
                startScannerActivity();
                break;
            case "isOnline":
                checkInternetConnection(result);
                break;
            case "getSupportPhone":
                result.success(BuildConfig.supportPhone);
                break;
            case "getSupportUrl":
                result.success(BuildConfig.supportUrl);
                break;
            case "getEndpoint":
                result.success(BuildConfig.endpoint);
                break;
            case "getAppToken":
                result.success(BuildConfig.appToken);
                break;
            case "getAppTitle":
                result.success(BuildConfig.appTitle);
                break;
            case "showBonus":
                result.success(BuildConfig.showBonus);
                break;
            default:
                result.notImplemented();
                break;
        }
    }

    private String getLanguage() {
        List<String> availableLanguages = Arrays.asList("ru", "en");
        if (availableLanguages.contains(Locale.getDefault().getLanguage())) {
            return Locale.getDefault().getLanguage();
        } else {
            return BuildConfig.locale;
        }
    }

    private void checkInternetConnection(Result result) {
        boolean connected = Utils.isOnline(this);
        if (!connected)
            Toast.makeText(this, "Проверьте интернет соединение", Toast.LENGTH_SHORT).show();
        result.success(connected);
    }

    private void setLocale(String locale) {
        locale = locale != null ? locale : getLanguage();
        Resources res = getResources();
        Configuration configuration = new Configuration(res.getConfiguration());
        configuration.locale = new Locale(locale);
        Locale.setDefault(configuration.locale);
        res.updateConfiguration(configuration, res.getDisplayMetrics());
    }

    private void startScannerActivity() {
        final int idx = getSharedPreferences("scanner", Context.MODE_PRIVATE).getInt(SCANNER_BACKEND_KEY, 0);
        Intent cameraIntent = new Intent(MainActivity.this, SCANNER_BACKEND[idx]);
        cameraIntent.putExtra(PREF_API_URL, (String) mScannerArgs.get("url"));
        cameraIntent.putExtra(PREF_APP_TOKEN, (String) mScannerArgs.get("appToken"));
        cameraIntent.putExtra(PREF_POS_TOKEN, (String) mScannerArgs.get("token"));
        cameraIntent.putExtra(PREF_APP_BAR_COLOR, (Long) mScannerArgs.get("color"));
        setLocale((String) mScannerArgs.get("locale"));
        startActivityForResult(cameraIntent, START_SCANNER_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == START_SCANNER_REQUEST_CODE) {
            if (resultCode == RESULT_CANCELED) {
                finish();
            } else if (resultCode == RESULT_OK) {
                if (data != null) {
                    String user = data.getExtras().getString("user", null);
                    if (user != null) {
                        String card = data.getExtras().getString("card", null);
                        ArrayList<String> args = new ArrayList<>(2);
                        args.add(user);
                        args.add(card);
                        mChannel.invokeMethod("purchase", args);
                    } else {
                        String menuItem = data.getExtras().getString("item", null);
                        if (menuItem != null) {
                            mChannel.invokeMethod(menuItem, null);
                        }
                    }
                } else {
                    startScannerActivity();
                }
            }
        }
    }

    public void getFlavor() {

    }

    public void getCurrency() {

    }

    public void getLocale() {

    }

    public void setUserLocale() {

    }

    public void startScanner() {

    }

    public void isOnline() {

    }

    public void getSupportPhone() {

    }

    public void getSupportUrl() {

    }

    public void getEndpoint() {

    }

    public void getAppToken() {

    }
}
