package com.example.calcutator.Calculator1;

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

import com.example.calcutator.R;

import androidx.annotation.DrawableRes;
import androidx.appcompat.app.AppCompatActivity;
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.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.HashMap;
import java.util.List;
import java.util.Random;

public class Calculator_1_1 extends AppCompatActivity {
    TableLayout tb;
    TableLayout tb1;
    TableRow tests;
    Integer calcul;
    private float mScale1;
    private int calwidth1;
    private EditText et1;
    private EditText et2;
    private EditText et3;
    private EditText et4;
    private EditText first;
    private EditText autoEdit;
    private int a;
    private int second;
    private List list;
    EditText[] SecondEdit;
    EditText[] ThirdEdit;
    EditText[] QuadEdit;
    Integer secondnum = 201;
    Integer thirdnum = 301;
    Integer quad=401;
    List list1;
    List list2;
    List list3;
    private int bar;
    private int sum = 0;
    private int sum3 = 0;
    private int sum2;
    private int o=0;
    boolean onoff=false;
    Integer cknums=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator_1_1);
        Intent intent = getIntent();
        bar = intent.getExtras().getInt("bars");
        calcul = Integer.valueOf(bar);
        tb = findViewById(R.id.table1);
        tb1 = findViewById(R.id.table2);

        list = new ArrayList();
        list1 = new ArrayList();
        list2 = new ArrayList();
        list3 = new ArrayList();
        int z=0;


        a=70;
        mScale1=getResources().getDisplayMetrics().density;
        calwidth1=(int)(a*mScale1);
        list.add(101);



        for (int i = 1; i <=calcul; i++) {
            TableRow row= new TableRow(this);
            TextView tv = new TextView(this);
            et1 = new EditText(this);
            et2 = new EditText(this);
            et3 = new EditText(this);
            et4 = new EditText(this);
            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);
            et4.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            tv.setWidth(calwidth1);
            et1.setWidth(calwidth1);
            et2.setWidth(calwidth1);
            et3.setWidth(calwidth1);
            et4.setWidth(calwidth1);

            et1.setIncludeFontPadding(false);
            et2.setIncludeFontPadding(false);
            et3.setIncludeFontPadding(false);
            et4.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));
            et4.setBackground(ContextCompat.getDrawable(this,R.drawable.border2));
            tv.setBackground(ContextCompat.getDrawable(this,R.drawable.border2));
            String strColor = "#434F69";
            tv.setTextColor(Color.parseColor(strColor));


            tv.setWidth(calwidth1);
            tv.setHeight(120);
            tv.setMaxHeight(120);
            tv.setGravity(Gravity.CENTER);
            tv.setText("GB"+i);
            et1.setWidth(calwidth1);
            et1.setGravity(Gravity.CENTER);
            et2.setWidth(calwidth1);
            et2.setGravity(Gravity.CENTER);
            et3.setWidth(calwidth1);
            et3.setGravity(Gravity.CENTER);
            et4.setWidth(calwidth1);
            et4.setGravity(Gravity.CENTER);
            et1.setId(100+i);
            et1.setHeight(120);
            et1.setMaxHeight(120);
            et2.setId(200+i);
            et2.setHeight(120);
            et2.setMaxHeight(120);
            et3.setId(300+i);
            et3.setHeight(120);
            et3.setMaxHeight(120);
            et4.setId(400+i);
            et4.setHeight(120);
            et4.setMaxHeight(120);
            row.addView(tv);
            row.addView(et1);
            row.addView(et2);
            row.addView(et3);
            row.addView(et4);
            list1.add(100+i);
            list2.add(200+i);
            list3.add(300+i);
            secondnum = 201;
            tb.addView(row,i);
        }
        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].setImeOptions(EditorInfo.IME_ACTION_NEXT);
            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 (int i = 0; i < bar; i++) {
            ThirdEdit[i] = findViewById(thirdnum+i);
            ThirdEdit[i].setImeOptions(EditorInfo.IME_ACTION_NEXT);
            ThirdEdit[i].setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if(actionId==EditorInfo.IME_ACTION_NEXT){
                        try {
                            ThirdEdit[sum2].setNextFocusForwardId(quad+sum2);
                            sum2 = sum2+1;
                        }catch (Exception e){
                            System.out.println(e);
                        }
                    }
                    return false;
                }
            });


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

            QuadEdit[o] = findViewById(quad+o);
            if (o>=bar-1){
                QuadEdit[o].setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if(actionId==EditorInfo.IME_ACTION_NEXT||o<bar){
                            try {
                                QuadEdit[sum3].setNextFocusForwardId(R.id.weight);
                            }catch (Exception e){
                                System.out.println(e);
                            }
                        }
                        return false;
                    }
                });
            }else {
                QuadEdit[o].setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if(actionId==EditorInfo.IME_ACTION_NEXT||o<bar){
                            try {
                                QuadEdit[sum3].setNextFocusForwardId(secondnum+1+sum3);
                                sum3 = sum3 + 1;
                            }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());



        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_3(View v) {
        cknums=cknums+1;
        try {
            System.out.println("-------------------------------------------------1");
            View view = findViewById(R.id.captures_1);
            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 weight_calculation(View v){
        float sums = 0;
        float hap = 0;
        float calcusum = 0;
        int milss = 0;
        int rackss = 0;
        int bonss = 0;
        int deniarss = 0;

            if(onoff==false){
                for(int i = 1; i<=calcul; i++){
                    EditText mil = findViewById(100+i);
                    EditText rack = findViewById(200+i);
                    EditText bon = findViewById(300+i);
                    EditText deniar = findViewById(400+i);
                try{
                    String S_mil=mil.getText().toString();
                    String S_rack=rack.getText().toString();
                    String S_bon=bon.getText().toString();
                    String S_deniar=deniar.getText().toString();
                    int mils = Integer.parseInt(S_mil);
                    int racks = Integer.parseInt(S_rack);
                    int bons = Integer.parseInt(S_bon);
                    int deniars = Integer.parseInt(S_deniar);
                    milss = mils;
                    rackss = racks;
                    bonss = bons;
                    deniarss = deniars;
                    float calcu1 = (float)(milss*91.44/480*rackss/9000/1000*bonss*deniarss);
                    int b=116;
                    float mScale2=getResources().getDisplayMetrics().density;
                    final int calwidth2=(int)(b*mScale2);
                    sums = calcu1+sums;
                    TableRow row = new TableRow(this);
                    TextView tbv1 = new TextView(this);
                    TextView tbv2 = new TextView(this);
                    TextView tbv3 = new TextView(this);

                    tbv1.setWidth(calwidth2);
                    tbv1.setGravity(Gravity.CENTER);
                    tbv2.setWidth(calwidth2);
                    tbv2.setHeight(150);
                    tbv2.setGravity(Gravity.CENTER);
                    tbv3.setWidth(calwidth2);
                    tbv3.setGravity(Gravity.CENTER);
                    tbv2.setId(500+i);
                    tbv3.setId(600+i);
                    tbv1.setText("GB" + i);
                    tbv2.setText(Float.toString(calcu1));
                    row.addView(tbv1);
                    row.addView(tbv2);
                    row.addView(tbv3);
                    tb1.addView(row, i);

                }catch(NumberFormatException e){
                    Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요",Toast.LENGTH_LONG).show();
                }catch (NullPointerException e){
                    Toast.makeText(this.getApplicationContext(),"값을 제대로 입력해 주세요",Toast.LENGTH_LONG).show();
                }

            try {

                for (int z = 1; z <= calcul; z++) {
                    TextView calcu1s = findViewById(500 + z);
                    TextView calcu2s = findViewById(600 + z);


                    float calcu1 = Float.parseFloat(calcu1s.getText().toString());
                    float calcu2 = calcu1 / sums * 100;
                    calcu2s.setText(Float.toString(calcu2));
                    calcusum = calcu2 + calcusum;
                }
                TableRow row= new TableRow(this);
                TextView tv1 = new TextView(this);
                TextView tv2 = new TextView(this);
                TextView tv3 = new TextView(this);
                tv1.setText("합계");
                tv1.setGravity(Gravity.CENTER);
                tv2.setText(Float.toString(sums));
                tv2.setGravity(Gravity.CENTER);
                tv2.setHeight(150);
                tv3.setText(Float.toString(calcusum));
                tv3.setGravity(Gravity.CENTER);
                row.addView(tv1);
                row.addView(tv2);
                row.addView(tv3);
                tb1.addView(row);
            }catch (NullPointerException e){

            }
            }
                onoff=true;
            }else{
                return;
            }



    }


}
