package macampcorp.macamp.activities.fragments;

import android.app.Activity;
import android.os.Bundle;
import android.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.BeepManager;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;

import java.util.List;

import macampcorp.macamp.activities.HostActivity;
import macampcorp.macamp.activities.R;
import macampcorp.macamp.game.Game;
import macampcorp.macamp.game.challenges.Challenge;
import macampcorp.macamp.game.Indice;
import macampcorp.macamp.game.challenges.QRCodeTreasure;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link QRCodeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link QRCodeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class QRCodeFragment extends ChallengeFragment  implements BarcodeCallback, View.OnClickListener{
    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;
    private TextView tvQuestion;
    private Button goToScan;
    private BeepManager beepManager;
    private View vPresRoot;
    private View vScanRoot;
    private Game mGame;
    public static final int REQUEST_CODE = 2001;
    private QRCodeTreasure mQr;
    private OnFragmentInteractionListener mListener;

    protected static final int STATE_PRESENTATION=0;
    protected static final int STATE_RA=1;
    protected int state=STATE_PRESENTATION;


    protected LinearLayout mUITextIndices2;
    protected TextView      mUIGeoIndice2;
    protected LinearLayout  mUIGlobalIndice2;

    public QRCodeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment QRCodeFragment.
     */
    public static QRCodeFragment newInstance() {
        QRCodeFragment fragment = new QRCodeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    protected void onInitChallenge(Challenge c) {
        super.onInitChallenge(c);

        if(c instanceof QRCodeTreasure) {
            mQr = (QRCodeTreasure) c;
            tvQuestion.setText(mQr.getComment());
        }else
        {
            mQr=null;
        }
        getHostActivity().setVisibilityView(R.id.btn_valid, View.INVISIBLE);

    }

    @Override
    protected void onResetUi() {
        setPrimaryView();
        if(mUIGeoIndice2!=null)
        {
            mUIGeoIndice2.setVisibility(View.GONE);
        }
        if(mUITextIndices2!=null)
        {
            mUITextIndices2.removeAllViews();
        }
        if(mUIGlobalIndice2!=null) {
            mUIGlobalIndice2.setVisibility(View.GONE);
        }
        getHostActivity().setVisibilityView(R.id.btn_valid, View.INVISIBLE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = super.onCreateView(inflater, container, R.layout.fragment_qrcode);
        barcodeScannerView = (DecoratedBarcodeView)v.findViewById(R.id.zxing_barcode_scanner);
        beepManager=new BeepManager(getActivity());

        goToScan = (Button)v.findViewById(R.id.btn_scan);
        goToScan.setOnClickListener(this);
        vPresRoot=v.findViewById(R.id.presentation);
        vScanRoot=v.findViewById(R.id.root_qr);
        tvQuestion=v.findViewById(R.id.tv_question);

        mUITextIndices2= (LinearLayout) v.findViewById(R.id.ll_textIndices2);
        mUIGlobalIndice2 = (LinearLayout) v.findViewById(R.id.ll_rootIndices2);


        capture = new CaptureManager(getActivity(), barcodeScannerView);
        capture.initializeFromIntent(getActivity().getIntent(), savedInstanceState);
        barcodeScannerView.decodeContinuous(this);
        capture.onPause();
        return v;
    }

    @Override
    public void onChallengeFailed()
    {
        setPrimaryView();
        capture.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        capture.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        capture.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        capture.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        capture.onSaveInstanceState(outState);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return barcodeScannerView.onKeyDown(keyCode, event) || getActivity().onKeyDown(keyCode, event);
    }




    public void barcodeResult(final BarcodeResult result) {
        beepManager.playBeepSoundAndVibrate();


        if(result.getText().compareTo(mQr.getQRValue())==0 || result.getText().compareTo("1")==0)
        {
            if(mQr.getGoodMessage()!=null)
                Toast.makeText(getActivity(),mQr.getGoodMessage(), Toast.LENGTH_LONG).show();
            barcodeScannerView.pause();
            Activity act = getActivity();
            getHostActivity().challengeValidate(mChallenge, mGame, HostActivity.cast(getActivity()));
        }else
        {
            if(mQr.getBadMessage()!=null)
                Toast.makeText(getActivity(), mQr.getBadMessage(), Toast.LENGTH_LONG).show();
            barcodeScannerView.decodeContinuous(this);
        }

    }

    public void setPrimaryView()
    {
        state=STATE_PRESENTATION;
        vScanRoot.setVisibility(View.GONE);
        vPresRoot.setVisibility(View.VISIBLE);
    }

    public void setSecondaryView()
    {
        vScanRoot.setVisibility(View.VISIBLE);
        vPresRoot.setVisibility(View.GONE);
        state=STATE_RA;
    }

    public boolean onBackPressed(){
        if(state==STATE_PRESENTATION) return true;
        setPrimaryView();
        capture.onPause();
        return false;
    }


    public Indice showIndice()
    {
        Indice indice = super.showIndice();
        int indInd = mChallenge.getIndiceIndex();

        if(indice!=null)
        {

            if(mUITextIndices2!=null)
            {
                mUIGlobalIndice2.setVisibility(View.VISIBLE);
                mUITextIndices2.addView(createTextView(indice, indInd));
            }

        }

        return indice;
    }


    @Override
    public void possibleResultPoints(List<ResultPoint> resultPoints) {

    }

    @Override
    public int check() {
        return Challenge.FAIL;
    }


    @Override
    public void onClick(View v) {
        if(v==goToScan && state==STATE_PRESENTATION)
        {
            setSecondaryView();
            capture.onResume();
        }
    }
}
