package beyondsoft.bewomitarbeiterapp;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.media.Image;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Created by bib on 03.05.2016.
 */
public class KontaktAdapter extends ArrayAdapter<ContactList> {

    private final Context context;
    private final ContactList[] values;
   // private final List<ContactList> contactlist;

    private Bitmap bitmaping;
    ImageView imageView;
    TextView minitext;

    private String[] filedaten;

    Thread getM;
    Thread getPic;


    public KontaktAdapter(Context context, ContactList[] values) {
        super(context, R.layout.kontakt_list_chat,values);
        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.kontakt_list_chat, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        minitext = (TextView) rowView.findViewById(R.id.subtitle);
       // TextView lasttime = (TextView) rowView.findViewById(R.id.lasttime);

        ImageView onlinestats = (ImageView)rowView.findViewById(R.id.status);
        imageView = (ImageView) rowView.findViewById(R.id.logo);

        // ImageView Bau die Kontakt View auf
        textView.setText(values[position].getKontaktName());


        //Textzuweisung auf die methode verlagern
        if(values[position].getKontaktName().equals("Demo")) {
            getM = new Thread(new ReadLastMessage(values[position].getKontaktName(), inflater));
            getM.start();
        }else
            minitext.setText("Hier könnte auch ihre Nachricht stehen");


        Log.v("Bis hierhin","Alles correct");

        //get last Message from File
        //filedaten =  ReadLastMessage(values[position].getKontaktName(),inflater);

        //abfrage mit demo ist provisorium weil zurzeit alle auf demo zugreifen würden
        /*if(values[position].getKontaktName().equals("Demo") && filedaten != null)
            minitext.setText(filedaten[0]);
        else
            minitext.setText("Hier könnte auch ihre Nachricht stehen");*/


        //lasttime.setText(filedaten[1]);

        //ab hier fehlerhaft
        if(values[position].getPicture() != null) {

            //Konvert byte[] to Image
            Bitmap i = BitmapFactory.decodeByteArray(values[position].getPicture(),0,values[position].getPicture().length);

            getPic = new Thread(new GetCircleBitmap(i));
            getPic.start();

           // t.interrupt();

            //imageView.setImageBitmap(bitmaping);
        }else {
            //wenn der kontakt kein bild besitzt dann nimm Default bild
            //Bitmap customerImage =((BitmapDrawable).getDrawable(R.drawable.katze3)).getBitmap();
            Bitmap bitmap = BitmapFactory.decodeResource(inflater.getContext().getResources(), R.drawable.katze3);
           // imageView.setImageResource(R.drawable.katze3);

            getPic = new Thread(new GetCircleBitmap(bitmap));
            getPic.start();



           // imageView.setImageBitmap(bitmaping);
        }

        //if statement ob kontakt online oder net
        if(values[position].getArt().equals("1"))
            onlinestats.setImageResource(R.drawable.online);
        else if(values[position].getArt().equals("2"))
            onlinestats.setImageResource(R.drawable.beschaftigt);
        else if(values[position].getArt().equals("3"))
            onlinestats.setImageResource(R.drawable.offline);


        return rowView;
    }


    public class GetCircleBitmap implements Runnable{

        Bitmap bitmap;
        GetCircleBitmap(Bitmap _bitmap){
            this.bitmap = _bitmap;
        }

        public void run(){
            final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Bitmap.Config.ARGB_8888);
            final Canvas canvas = new Canvas(output);

            final int color = Color.RED;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
            final RectF rectF = new RectF(rect);

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawOval(rectF, paint);

            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);

            bitmap.recycle();

            bitmaping = output;

            Log.v("GET Circled"," Picture");

            //if(imageView != null)
            //    imageView.setImageBitmap(output);


            imageView.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setImageBitmap(bitmaping);

                }
            });


        }
    }


    //Convert Bitmap for a circled bitmap
    /*private Bitmap GetCircleBitmap(Bitmap bitmap ) {
        final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(output);

        final int color = Color.RED;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawOval(rectF, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        bitmap.recycle();

        return output;
    }*/



    public class ReadLastMessage implements Runnable{

        LayoutInflater inflater;
        String filename;

        ReadLastMessage(String _filename,LayoutInflater _inflater){
            this.inflater = _inflater;
            this.filename = _filename;
        }

        public void run(){

            try{
                File filesDir = inflater.getContext().getFilesDir();

                File file = new File(filesDir, "demo" +".txt");  //---->filename

                FileInputStream stream = new FileInputStream(file);

                InputStreamReader in = new InputStreamReader(stream);

                BufferedReader readLn = new BufferedReader(in);

                String line = readLn.readLine();
                String allLines="";

                String [] ret= new String[2];

                while (line != null) {
                    allLines += line;

                    String[] splitt = line.split("/");

                    if(splitt.length >1 ) {
                        String[] ArtDate = splitt[1].split("%");

                        final String message = splitt[0];

                        final boolean art = Boolean.valueOf(ArtDate[0]);

                        final String datetime = ArtDate[1];

                        if(!art) {
                            ret[0] = message;
                            ret[1] = datetime;
                        }
                    }
                    line = readLn.readLine();
                }

                stream.close();
                in.close();


               // filedaten =ret;


                if(minitext != null)
                    minitext.setText(ret[0]);

            }catch(Exception e){
                Log.v("Fehler 2 ",e.getMessage());
                e.printStackTrace();
               // return null;
            }





        }
    }


    public String[] ReadLastMessage(String filename,LayoutInflater inflater){
        try{
            File filesDir = inflater.getContext().getFilesDir();

            File file = new File(filesDir, "demo" +".txt");  //---->filename

            FileInputStream stream = new FileInputStream(file);

            InputStreamReader in = new InputStreamReader(stream);

            BufferedReader readLn = new BufferedReader(in);

            String line = readLn.readLine();
            String allLines="";

            String [] ret= new String[2];

            while (line != null) {
                allLines += line;

                String[] splitt = line.split("/");

                if(splitt.length >1 ) {
                    String[] ArtDate = splitt[1].split("%");

                    final String message = splitt[0];

                    final boolean art = Boolean.valueOf(ArtDate[0]);

                    final String datetime = ArtDate[1];

                    if(!art) {
                        ret[0] = message;
                        ret[1] = datetime;
                    }
                }
                line = readLn.readLine();
            }

            stream.close();
            in.close();

            return ret;

        }catch(Exception e){
            Log.v("Fehler 2 ",e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
