package kz.arta.synergy.workflow.mobile.android.authorization.activities;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.widget.TextView;

import com.devspark.appmsg.AppMsg;
import com.dlazaro66.qrcodereaderview.QRCodeReaderView;

import kz.arta.synergy.workflow.mobile.android.R;
import kz.arta.synergy.workflow.mobile.android.authorization.SynergyAccount;
import kz.arta.synergy.workflow.mobile.android.common.requests.RestClient;
import kz.arta.synergy.workflow.mobile.android.common.utils.Fonts;

/**
 * Created by neox on 22.11.15.
 * Экран для сканирования QR-кода
 */
public class QrCodeActivity extends Activity implements QRCodeReaderView.OnQRCodeReadListener {

    private Activity activity;

    /**
     * QR ридер
     */
    private QRCodeReaderView qrCodeReaderView;

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

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        activity = this;

        ((TextView) findViewById(R.id.qr_code_activity_title1)).setTypeface(Fonts.getRoman(this));
        ((TextView) findViewById(R.id.qr_code_activity_title2)).setTypeface(Fonts.getRoman(this));

        qrCodeReaderView = (QRCodeReaderView) findViewById(R.id.qr_code_scanner);
        qrCodeReaderView.setOnQRCodeReadListener(this);
    }

    @Override
    public void onQRCodeRead(String text, PointF[] points) {
        try {
            AuthJson json = RestClient.getGson().fromJson(text, AuthJson.class);
            Intent intent = new Intent();
            intent.putExtra(SynergyAccount.HOST, json.host);
            intent.putExtra(SynergyAccount.LOGIN, json.login);
            setResult(RESULT_OK, intent);
            finish();
        } catch (Exception exc) {
            AppMsg.makeTextBottom(activity, "Ошибка сканирования QR-кода").show();
        }
    }

    @Override
    public void cameraNotFound() {

    }

    @Override
    public void QRCodeNotFoundOnCamImage() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        qrCodeReaderView.getCameraManager().startPreview();
    }

    @Override
    protected void onPause() {
        super.onPause();
        qrCodeReaderView.getCameraManager().stopPreview();
    }

    /**
     * Сервер возвращает QR код со следующими параметрами
     */
    class AuthJson {

        /**
         * Логин
         */
        String login;

        /**
         * Хост
         */
        String host;
    }
}