package com.example.calcutator.Calculator1;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import com.example.calcutator.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

import android.os.Environment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Calculator_1_3 extends AppCompatActivity {
    TableLayout table;
    Integer calcul = 0;
    private EditText et1;
    private EditText et2;
    private EditText et3;
    private EditText first;
    private EditText autoEdit;
    EditText testwet;
    private EditText weights;
    Integer secondnum = 201;
    Integer thirdnum = 301;
    EditText[] SecondEdit;
    EditText[] ThirdEdit;
    private int second;
    private int test;
    private int bar;
    private int sum = 0;
    private int sum2;
    private int o=0;
    Integer cknums=0;
    List list;
    List list1;
    List list2;
    List list3;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator_1_3);
        table = findViewById(R.id.table1);
        Intent intent = getIntent();
        bar = intent.getExtras().getInt("bars");
        calcul = Integer.valueOf(bar);
        sum=0;
        sum2=0;
        list = new ArrayList();
        list1 = new ArrayList();
        list2 = new ArrayList();
        list3 = new ArrayList();

        int z=0;
        list.add(101);

        int a=80;
        int b=70;
        int c=100;

        float mScale1=getResources().getDisplayMetrics().density;
        final int calwidth1=(int)(a*mScale1);

        float mScale2=getResources().getDisplayMetrics().density;
        final int calwidth2=(int)(b*mScale1);

        float mScale3=getResources().getDisplayMetrics().density;
        final int calwidth3=(int)(c*mScale1);

        for(int i=1; i<=bar; i++){
            Integer znum = 0;
            TableRow row = new TableRow(this);
            TextView barnum = new TextView(this);
             et1 = new EditText(this);
             et2 = new EditText(this);
             et3 = new EditText(this);


            String strColor = "#434F69";
            barnum.setTextColor(Color.parseColor(strColor));

            et1.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            et2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            et3.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);


            et1.setWidth(calwidth1);
            et2.setWidth(calwidth1);
            et3.setWidth(calwidth1);

            et1.setIncludeFontPadding(false);
            et2.setIncludeFontPadding(false);
            et3.setIncludeFontPadding(false);

            et1.setBackground(ContextCompat.getDrawable(this,R.drawable.border2));
            et2.setBackground(ContextCompat.getDrawable(this,R.drawable.border2));
            et3.setBackground(ContextCompat.getDrawable(this,R.drawable.border2));
            barnum.setBackground(ContextCompat.getDrawable(this,R.drawable.border2));
            barnum.setWidth(calwidth1);
            et1.setWidth(calwidth1);
            et2.setWidth(calwidth1);
            et3.setWidth(calwidth1);
            TextView prices = new TextView(this);
            barnum.setText("GB"+i);
            barnum.setGravity(Gravity.CENTER);
            barnum.setWidth(calwidth1);
            barnum.setHeight(120);
            barnum.setMaxHeight(120);
            et1.setId(100+i);
            et1.setWidth(calwidth1);
            et1.setHeight(120);
            et1.setMaxHeight(120);
            et1.setGravity(Gravity.CENTER);
            et1.setHint("%");
            et2.setId(200+i);
            et2.setWidth(calwidth1);
            et2.setHeight(120);
            et2.setMaxHeight(120);
            et2.setGravity(Gravity.CENTER);
            et2.setHint("won");
            et3.setId(300+i);
            et3.setWidth(calwidth1);
            et3.setHeight(120);
            et3.setMaxHeight(120);
            et3.setHint("%");
            et3.setGravity(Gravity.CENTER);
            prices.setId(400+i);
            prices.setText("");
            prices.setWidth(calwidth1);
            prices.setGravity(Gravity.CENTER);
            prices.setHeight(120);
            prices.setMaxHeight(120);
            prices.setBackground(ContextCompat.getDrawable(this,R.drawable.border2));
            row.addView(barnum);
            row.addView(et1);
            row.addView(et2);
            row.addView(et3);
            row.addView(prices);
            list1.add(100+i);
            list2.add(200+i);
            list3.add(300+i);
            table.addView(row,i);
            secondnum = 201;

        }

        first = (EditText)findViewById(Integer.parseInt(list.get(z).toString()));
        first.requestFocus();

        SecondEdit = new EditText[bar];
        for (int i = 0; i < bar; i++) {
            SecondEdit[i] = findViewById(secondnum+i);

                SecondEdit[i].setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if(actionId==EditorInfo.IME_ACTION_NEXT){
                            try {
                                SecondEdit[sum].setNextFocusForwardId(thirdnum+sum);
                                sum = sum+1;
                            }catch (Exception e){
                                System.out.println(e);
                            }
                        }
                        return false;
                    }
                });


        }
        ThirdEdit = new EditText[bar];
        for(o = 0; o < bar; o++){

            ThirdEdit[o] = findViewById(thirdnum+o);
                if (o==bar-1){
                    ThirdEdit[o].setOnEditorActionListener(new TextView.OnEditorActionListener() {
                        @Override
                        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                            if(actionId==EditorInfo.IME_ACTION_NEXT||o<bar){
                                try {
                                    ThirdEdit[sum2].setNextFocusForwardId(R.id.weight);
                                }catch (Exception e){
                                    System.out.println(e);
                                }
                            }
                            return false;
                        }
                    });
                }else {
                    ThirdEdit[o].setOnEditorActionListener(new TextView.OnEditorActionListener() {
                        @Override
                        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                            if(actionId==EditorInfo.IME_ACTION_NEXT||o<bar){
                                try {
                                    ThirdEdit[sum2].setNextFocusForwardId(secondnum+1+sum2);
                                    sum2 = sum2 + 1;
                                    System.out.println(o);
                                    System.out.println("--------------------------------4");
                                    System.out.println("--------------------------------4");

                                }catch (Exception e){
                                    System.out.println(e);
                                }
                            }
                            return false;
                        }
                    });
                }


        }
        //ThirdEdit=(EditText)findViewById(Integer.parseInt(list3.get(z+sum2).toString()));
        first.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                for(int i=1;i<bar;i++){
                    autoEdit = (EditText)findViewById(Integer.parseInt(list1.get(i).toString()));
                    autoEdit.setText(first.getText());
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                for(int i=1;i<bar;i++){
                    autoEdit = (EditText)findViewById(Integer.parseInt(list1.get(i).toString()));
                    autoEdit.setText(first.getText());
                }
            }
        });

        second = Integer.parseInt(list2.get(z).toString());
        test = Integer.parseInt(list3.get(0).toString());


        first.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    first.setNextFocusRightId(second);

                    return true;
                }
                return false;
            }
        });


    }
    public void setScreenCapture(View v) {
        cknums=cknums+1;
        try {
            System.out.println("-------------------------------------------------1");
            View view = findViewById(R.id.captures);
            view.buildDrawingCache();
            // 긴 화면도 가져오기 위한 함수 호출

            Bitmap bitmap = loadBitmapFromView(view);

            if(cknums==2 && bitmap!=null) {
                // 저장 하기 위한 함수 호출
                screenshot(bitmap);
                //저장 완료
            }else if(cknums==1) {
                //수정필요
                Toast.makeText(this.getApplicationContext(),"다시 한번 눌러주세요",Toast.LENGTH_SHORT);
            }else if(cknums>2){
                //수정필요
                Toast.makeText(this.getApplicationContext(),"이미 저장되었습니다",Toast.LENGTH_SHORT);
            }
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
            Toast mToast= Toast.makeText(this.getApplicationContext(),"사진저장에실패하셨습니다",Toast.LENGTH_SHORT);
            mToast.show();
        }
    }
    // 긴 화면도 가져오기 위한 함수
    public static Bitmap loadBitmapFromView(View v){
        System.out.println("-------------------------------------------------2");
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.layout(-725, 0, 1800, v.getLayoutParams().height);
        v.draw(c);
        return b;
    }
    public void screenshot(Bitmap bm){
        System.out.println("-------------------------------------------------3");
        String extr = Environment.getExternalStorageDirectory().toString();
        File mFolder = new File(extr + "/TexCalculator");
        // 해당 폴더가 없으면 생성
        if (!mFolder.exists()) {
            mFolder.mkdir();
        }
        Random random = new Random();
        String s = "TexCalculator_" + String.valueOf( random.nextInt(99999)) + ".png";
        File file = new File(mFolder.getAbsolutePath(), s);
        FileOutputStream fos = null;
        try {
            System.out.println("-------------------------------------------------4");
            fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void calcul3(View v){
        float sums1= 0;
        float sums2= 0;
        float sums3 = 0;
        try{

            for(int i=1; i<=calcul; i++){

                EditText hons = findViewById(100+i);
                EditText pounds = findViewById(200+i);
                EditText losss = findViewById(300+i);
                weights = findViewById(R.id.weight);
                TextView totals = findViewById(R.id.total);
                EditText outputs = findViewById(R.id.output);
                EditText Earningss = findViewById(R.id.Earnings);
                TextView rent = findViewById(R.id.rent);
                TextView papertotals = findViewById(R.id.papertotal);
                TextView hontotal = findViewById(R.id.hontotal);
                TextView poundtotal = findViewById(R.id.poundtotal);
                TextView barpricetotal = findViewById(R.id.barpricetotal);
                EditText salesmargins = findViewById(R.id.salesmargin);
                TextView prices = findViewById(400+i);
                Float hon = Float.parseFloat(hons.getText().toString());
                Float pound = Float.parseFloat(pounds.getText().toString());
                Float loss = Float.parseFloat(losss.getText().toString());
                Float weight = Float.parseFloat(weights.getText().toString());
                Float output = Float.parseFloat(outputs.getText().toString());
                Float Earnings = Float.parseFloat(Earningss.getText().toString());
                Float salesmargin = Float.parseFloat(salesmargins.getText().toString());

                float calcul1 = (float)(pound*(weight*(hon/100)*(100+loss)/453.592/100));
                double calculround1 = Math.round(calcul1);
                sums1 = hon + sums1;
                sums2 = pound + sums2;
                sums3 = calcul1 + sums3;
                prices.setText(calculround1+"원");
                System.out.println("test");
                if(i==calcul){
                    float calcul3 = Earnings/output;
                    double calculround3 = Math.round(calcul3);
                    float calcul2 = sums3 + calcul3+ salesmargin;
                    double calculround2 = Math.round(calcul2);

                    /* 합산 부분 반올림 */
                    double sumsround1 = Math.round(sums1);
                    double sumsround2 = Math.round(sums2);
                    double sumsround3 = Math.round(sums3);

                    rent.setText(calculround3+"원");
                    papertotals.setText(sumsround3+"원/Y");
                    totals.setText(calculround2+"원/Y");
                    hontotal.setText(sumsround1+"%");
                    poundtotal.setText(sumsround2+"원");
                    barpricetotal.setText(sumsround3+"원");
                }
            }
        }catch (NumberFormatException e){
            Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요", Toast.LENGTH_LONG).show();
        }catch (Exception e){
            Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요2", Toast.LENGTH_LONG).show();
        }

    }



}
