package app.mar.activities;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

import app.mar.game.Area;
import app.mar.game.Game;
import app.mar.game.Resource;
import app.mar.game.Stage;
import app.mar.game.challenges.Challenge;
import app.mar.game.challenges.Indice;
import app.mar.utils.AndroidResources;
import app.mar.utils.L;


public class HostActivity extends Activity implements ChallengeDriver{
    protected Game mGame;
    protected TextView mUITimeLeft;
    protected TextView mUICode;
    protected Button   mUIButtonVideos;
    protected Button   mUIButtonIndice;
    protected Button   mUIButtonValid;
    private Timer mTimer;

    protected QCMFragment mQCMFragment;
    protected QRCodeFragment mQRCodeFragment;
    protected QuestionFragment mQuestionFragment;
    protected ChallengeFragment mCurrentFragment;

    private Runnable mTimerTick = new Runnable() {
        public void run() {
            if(!mGame.getBomb().hasExplosed())
            {
                mUITimeLeft.setText(mGame.getBomb().getTimeBeforeBoom());
            }else
            {
                mUITimeLeft.setText("BOOM !");
                onExplose();
                mTimer.cancel();
            }
        }
    };

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

        mQCMFragment = QCMFragment.newInstance();
        mQuestionFragment = QuestionFragment.newInstance();
        mQRCodeFragment = QRCodeFragment.newInstance();
        mUIButtonVideos = (Button) findViewById(R.id.btn_videos);
        mUIButtonIndice = (Button) findViewById(R.id.btn_indice);
        mUIButtonValid = (Button) findViewById(R.id.btn_valid);

        mGame=Game.game();


        mUITimeLeft = findViewById(R.id.tv_car);
        mUICode = findViewById(R.id.tv_code);

        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                timerCallback();
            }

        }, 0, 1000);

        updateCode();

        startChallenge();

    }

    public   void setFragment(Class type)
    {
        ChallengeFragment f = null;

        if(type.isInstance(mQCMFragment))
            f= mQCMFragment;
        else if(type.isInstance(mQRCodeFragment))
            f= mQRCodeFragment;
        else if(type.isInstance(mQuestionFragment))
            f= mQuestionFragment;
        else {
            throw new RuntimeException("Erreur: La classe de fragment est null");
        }

        if(f!=mCurrentFragment)
        {
            mCurrentFragment=f;
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.container, mCurrentFragment);
            ft.commit();
        }
        else
        {
            onReady();
        }
    }

    @Override
    public void onReady() {
        Challenge chall = mGame.getCurrentChallenge();
        mCurrentFragment.initChallenge(chall);
    }



    @Override
    public double getDistanceWith(Area a) {
        return a.getDistance(mGame.getPlayer());
    }


    @Override
    public void onFragmentInteraction(Uri uri) {

    }


    private void timerCallback()
    {
        this.runOnUiThread(mTimerTick);
    }

    private void updateCode()
    {
        mUICode.setText(mGame.getBomb().getPasswordKnown());
    }

    public void onClickValid(View v)
    {
        if(mCurrentFragment!=null)
        {
            if(mCurrentFragment.check())
            {
                challengeValidate(mCurrentFragment.getChallenge());
            }
        }
    }


    public void onClickVideos(View v)
    {
        Intent intent = new Intent(this, ResourceListActivity.class);
        intent.putExtra("inventaire", mGame.getInventaire());
        startActivity(intent);
    }

    public void onClickDisarm(View v)
    {

    }

    public void onClickIndice(View v)
    {
        if(mCurrentFragment!=null)
        {
            Indice ind = mCurrentFragment.showIndice();
            if(ind!=null && ind.getPenality()>0)
                mGame.getBomb().addTime(-ind.getPenality());

            if(!mCurrentFragment.getChallenge().hasNextIndice())
                mUIButtonIndice.setVisibility(View.INVISIBLE);
        }
    }

    public void onExplose()
    {

    }


    public void setVisibilityView(int res, int state)
    {
        View v = findViewById(res);
        if(v!=null) v.setVisibility(state);
    }


    public void setVisibilityView(int[] res, int state)
    {
        for(int i=0; i<res.length; i++)
            setVisibilityView(res[i], state);
    }


    public void nextChallenge() {
        Stage s = mGame.getCurrentStage();
        Challenge c = s.nextChallenge();
        if(c!=null)
        {
            startChallenge();
        }else //new stage
        {
            if(mGame.nextStage()!=null)
                startChallenge();
        }
    }

    public void startResourceFound()
    {
        Resource r = null;
        while( (r=mGame.popLastResource())!=null )
        {
            Intent intent = AndroidResources.getViewerIntent(this, r);
            startActivity(intent);
        }
    }

    @Override
    public void challengeValidate(Challenge c) {
        c.setDone();
        nextChallenge();
    }

    public Challenge currentChallenge() {
        return mGame.getCurrentChallenge();
    }

    private boolean startChallenge()
    {
        boolean b=false;
        int res[] = {R.id.btn_indice, R.id.btn_valid, R.id.btn_videos};
        for(int i=0; i<res.length; i++)
        {
            View v = findViewById(res[i]);
            v.setVisibility(View.VISIBLE);
        }

        Challenge c = mGame.getCurrentChallenge();
        if(c!=null) {
            c.exec(this);
            b=true;
        }
        startResourceFound();
        return b;
    }


    @Override
    public void startLocalisation() {
        mGame.newSensorManager(this);
    }

    @Override
    public void resumeLocalisation() {
        mGame.onResume();
    }

    @Override
    public void pauseLocalisation() {
        mGame.onPause(this);
    }


}
