package app.brest.testmin3d;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import app.brest.app.brest.ui.CameraPreview;
import app.brest.utils.JSONLoader;
import app.brest.utils.ResourceManager;
import app.brest.utils.SensorsManager;
import app.brest.utils.app.brest.game.Game;
import app.brest.utils.app.brest.game.Resource;
import min3d.core.Object3d;
import min3d.core.Object3dContainer;
import min3d.core.RendererActivity;
import min3d.parser.IParser;
import min3d.parser.Parser;
import min3d.vos.Light;
import min3d.vos.Number3d;


public class ARActivity extends RendererActivity
{

    private CameraPreview mImageSurfaceView;
    private Camera camera;
    private FrameLayout cameraPreviewLayout;

    private Object3dContainer faceObject3D;
    private Button mOkButton;
    private TextView mAngle;
    private TextView mGps;
    private final Object mLock = new Object();
    protected boolean isPausing=false;

    private Game mGame;


    public void init()
    {
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


        cameraPreviewLayout = (FrameLayout)findViewById(R.id.camera_preview);

        camera = checkDeviceCamera();
        mImageSurfaceView = new CameraPreview(ARActivity.this, camera);

        mAngle = (TextView) findViewById(R.id.angle);
        mGps = (TextView) findViewById(R.id.gps);


        mOkButton = (Button) findViewById(R.id.button_catch);
        mOkButton.setVisibility(View.INVISIBLE);

    }

    private Camera checkDeviceCamera() {
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mCamera;
    }

    protected void onCreateSetContentView()
    {
        init();
        cameraPreviewLayout.addView(mImageSurfaceView,0);
        cameraPreviewLayout.addView(_glSurfaceView,1);

    }

    @Override
    protected void glSurfaceViewConfig()
    {
        // !important
        _glSurfaceView.setEGLConfigChooser(8,8,8,8, 16, 0);
        _glSurfaceView.getHolder().setFormat(PixelFormat.TRANSLUCENT);
    }

    @Override
    public void initScene()
    {
        // !important
        scene.backgroundColor().setAll(0x00000000);
        scene.lights().add(new Light());
        scene.lights().add(new Light());

        Light myLight = new Light();
        myLight.position.setZ(150);
        scene.lights().add(myLight);


        //IParser myParser = Parser.createParser(Parser.Type.OBJ, getResources(), "app.brest.testmin3d:raw/face_obj", true);
        //myParser.parse();



    }

    protected Number3d pos(float deltaAngle, int _radius)
    {
        float radius = _radius;
        return new Number3d((float)(radius*Math.sin(deltaAngle)),
                            0,
                            (float)(15+radius*Math.cos(deltaAngle))
                        );
    }

    protected boolean updateSceneResource()
    {

        ArrayList<Resource> res = mGame.getResourcesNextToPlayer();
        final TextView tv = (TextView) findViewById(R.id.text_detected);
        final TextView tv2 = (TextView)findViewById(R.id.text_place);
        String toDisplay ="Detetected \n";
       // String dete = "Detected:\n";
        scene.clear();
        for (int i = 0; i < res.size(); i++) {
            Resource rr = res.get(i);
            toDisplay+="\t"+rr.getName()+" \n";
            //dete += "\t" + rr.getName() + "\n";
            Object3d oo = rr.get3DModel(this);
            scene.addChild(oo);
        }
        final String td = toDisplay;
        mAngle.getHandler().post(new Runnable() {
            public void run() {
                tv2.setText(td);
            }
        });

        final String dete2 = mGame.getResourcesNextToPlayer2();
        tv.getHandler().post(new Runnable() {
            public void run() {
                tv.setText(dete2);
            }
        });


        return scene.numChildren()>0;
    }
     @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        Game g = Game.load(this);

        if(getIntent().hasExtra("game_name"))
        {
            String n = getIntent().getStringExtra("game_name");
            mGame = new Game(n, this);
        }else if (g!= null) {
            mGame = g;
            mGame.newSensorManager(this);
        }else
        {
            throw new Error("Le jeu n'est pas sauvegardé");
        }

    }



    @Override
    /**
     * Verifie si on doit afficher des resources et gere le bouton de capture
     */
    public  void updateScene()
    {
        boolean isResource = false;
        synchronized (mLock) {
            if (!isPausing) {
                boolean b = mGame.precache3DResource(this);
                isResource = updateSceneResource();
                if(b)
                {
                    final Activity _this = this;
                    mAngle.getHandler().post(new Runnable() {
                        public void run() {
                            Toast.makeText(_this,"Localisé dans la zone", Toast.LENGTH_LONG);
                        }
                    });

                }
            }else
            {
                scene.clear();
                mGame.removeCached3DModels();
            }
        }

        if(isResource) {
            mOkButton.getHandler().post(new Runnable() {
                public void run() {
                    mOkButton.setVisibility(View.VISIBLE);
                }
            });
        }else
        {
            mOkButton.getHandler().post(new Runnable() {
                public void run() {
                    mOkButton.setVisibility(View.INVISIBLE);
                }
            });

        }
        mAngle.getHandler().post(new Runnable() {
            public void run() {
                mAngle.setText("Angle X: "+mGame.getPlayer().getOrientation()+"°\n Angle Y: "+
                                mGame.getPlayer().getOrientationY()
                                +"\n Angle Z: "+mGame.getPlayer().getOrientationZ()+"°");
            }
        });

    }


    @Override
    protected  void onResume() {
        super.onResume();
        mGame.onResume(this);
        scene.clear();

        synchronized (mLock)
        {
            isPausing=false;
        }
    }
    @Override
    protected  void onPause()
    {
        synchronized (mLock)
        {
            isPausing=true;
        }
        super.onPause();
        mGame.onPause(this);
        scene.clear();

    }

    public void setGpsText(final double lat, final double lon)
    {
        mGps.getHandler().post(new Runnable() {

            public void run() {
                mGps.setText("Latitude: "+lat+"°\n Longitude: "+lon+"\n");
            }
        });
    }

    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state
        savedInstanceState.putSerializable("game", mGame);

        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }

    public void onClickPickUp(View v)
    {
        boolean stageFinished = mGame.pickResource();
        boolean finished = false;

        //TDOD: Nouvelle activité pour afficher la ressource

        if(stageFinished)
        {
           finished = mGame.nextStage();
        }

        if(finished)
        {

        }

    }


    public void logCuurentAreas()
    {

    }

}
