package com.zimascience.drmf;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.maps.android.data.Feature;
import com.google.maps.android.data.kml.KmlContainer;
import com.google.maps.android.data.kml.KmlLayer;
import com.google.maps.android.data.kml.KmlPlacemark;
import com.google.maps.android.data.kml.KmlPolygon;
import com.google.maps.android.heatmaps.HeatmapTileProvider;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.AsyncHttpResponse;
import com.koushikdutta.async.http.body.MultipartFormDataBody;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class Gridshow2 extends FragmentActivity implements OnMapReadyCallback  {

    public GoogleMap mMap;
    int position2 = 0;
    int mapinit = 0;
    int mapinit2 = 0;

    GoogleApiClient mGoogleApiClient;

    String Year = "";
    String Month = "";

    double[] Lons = {50.6, 51.12, 51.11, 51.23, 51.27, 51.09, 51.30, 50.78, 51.1, 50.53, 51.42, 50.83,
            50.23, 51.47, 51.21, 51.46, 51.94, 51.76, 51.88, 52.32, 51.65, 51.36, 52.06, 51.78, 51.56, 51.69, 52.61,
            52.06, 51.76};
    double[] Lats = {29.61, 29.57, 29.38, 29.26, 29.46, 29.31, 28.88, 29.55, 28.5, 29.63, 29.14, 28.97, 30.1,
            29.25, 29.13, 28.9, 27.83, 28.39, 28.19, 27.82, 29, 28.65, 28.03, 28.51, 28.2, 28.83, 27.47, 27.87, 28.06};

    String[] Stname = {"عباسي", "جره بالا", "سعدآباد", "برازجان", "سرقنات", "كلل", "اهرم", "چهارروستايي",
            "عامري", "چاه بردي", "بزپر", "بوشهر", "بنه خاطر", "رودفارياب", "سمل-بنداروز", "فارياب",
            "دير", "شنبه", "باغان",
            "جم", "دهرود", "خورموج", "ريز", "کناربندک", "کناري", "بوشکان", "بندر عسلويه", "كنگان", "آبدان"};

    String[] Stname2 = {"St1", "St2", "St3", "St4", "St5", "St6", "St7", "St8", "St9", "St10", "St11", "St12", "St13",
            "St14", "St15", "St16", "St17", "St18", "St19", "St20", "St21", "St22", "St23", "St24", "St25", "St26", "St27",
            "St28", "St29"};

    final double[] intArraym1 = new double[Stname2.length];

    public double[] MinmaxST = new double[2];

    private HeatmapTileProvider mProvider;
    private TileOverlay mOverlay;

    private static final int ALT_HEATMAP_RADIUS = 20;


    int[] colors = {
            Color.rgb(102, 225, 0), // green
            Color.rgb(255, 0, 0)    // red
    };

    float[] startPoints = {
            0.2f, 1f
    };

    View V1;

    double Min;
    double Max;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gridshow2);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


        Spinner spinner = (Spinner) findViewById(R.id.spinner);


    }


    protected GoogleMap getMap() {
        return mMap;
    }


    protected int getLayoutId() {
        return R.layout.activity_st__annual__circ1;
    }


    private void retrieveFileFromResource() {
        try {
            KmlLayer kmlLayer = new KmlLayer(mMap, R.raw.bushehr1, getApplicationContext());

            Log.i("kml", "red kml");

            kmlLayer.addLayerToMap();
            //moveCameraToKml(kmlLayer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        Log.i("kml", "final of red kml");
    }


    private void moveCameraToKml(KmlLayer kmlLayer) {
        //Retrieve the first container in the KML layer
        KmlContainer container = kmlLayer.getContainers().iterator().next();
        //Retrieve a nested container within the first container
        container = container.getContainers().iterator().next();
        //Retrieve the first placemark in the nested container
        KmlPlacemark placemark = container.getPlacemarks().iterator().next();
        //Retrieve a polygon object in a placemark
        KmlPolygon polygon = (KmlPolygon) placemark.getGeometry();
        //Create LatLngBounds of the outer coordinates of the polygon
        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (LatLng latLng : polygon.getOuterBoundaryCoordinates()) {
            builder.include(latLng);
        }

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        getMap().moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), width, height, 1));
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    private class DownloadKmlFile extends AsyncTask<String, Void, byte[]> {
        private final String mUrl;

        public DownloadKmlFile(String url) {
            mUrl = url;
        }

        protected byte[] doInBackground(String... params) {
            try {
                InputStream is = new URL(mUrl).openStream();
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                int nRead;
                byte[] data = new byte[16384];
                while ((nRead = is.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
                }
                buffer.flush();
                return buffer.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(byte[] byteArr) {
            try {
                KmlLayer kmlLayer = new KmlLayer(mMap, new ByteArrayInputStream(byteArr),
                        getApplicationContext());
                kmlLayer.addLayerToMap();
                kmlLayer.setOnFeatureClickListener(new KmlLayer.OnFeatureClickListener() {
                    @Override
                    public void onFeatureClick(Feature feature) {

                        if (!Gridshow2.this.isFinishing()) {
                            Toast.makeText(Gridshow2.this,
                                    "Feature clicked: " + feature.getId(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                moveCameraToKml(kmlLayer);
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        doOnMap();

    }


    void doOnMap() {

        Log.i("Condition", "1");

        final String[] WWsitu = getIntent().getExtras().getStringArray("WhichWin2");

        if (mapinit == 0) {
            plot_Annual_Circl(WWsitu[4], WWsitu[5], WWsitu);
            Log.i("Condition", "2");
            mapinit = 1;
        }

        //double[] intArraymData_1 = getIntent().getExtras().getDoubleArray("Data_mapData");

        final ArrayList<Integer> DateData = new ArrayList<>(getIntent().getExtras().getIntegerArrayList("DateCond"));
        //final String[] WWsitu = getIntent().getExtras().getStringArray("WhichWin2");

        final ArrayList<String> DateLatLon = new ArrayList<>(getIntent().getExtras().getStringArrayList("LatLongrid"));

        final double[] intArraymLat_1 = new double[DateLatLon.size() / 2];
        final double[] intArraymLon_1 = new double[DateLatLon.size() / 2];
        final double[] intArraymData_1 = new double[DateLatLon.size() / 2];
        //double[] rowData = getIntent().getExtras().getDoubleArray("Data_Annaul_precip_Circ");

        //double[] intArraymLon_1 = getIntent().getExtras().getDoubleArray("Data_mapLon");
        int u11 = 0;
        int u22 = 1;
        for (int be = 0; be < (DateLatLon.size() / 2); be++) {
            intArraymLat_1[be] = Double.parseDouble(DateLatLon.get(u11));
            intArraymLon_1[be] = Double.parseDouble(DateLatLon.get(u22));
            u11 = u11 + 2;
            u22 = u22 + 2;

            double S1 = 0;
            double S2 = 0;


            for (int jj = 0; jj < Lons.length; jj++) {
                S1 = (intArraym1[jj] / (Math.pow(Math.abs(Lons[jj] - intArraymLon_1[be]), 2) +
                        Math.pow(Math.abs(Lats[jj] - intArraymLat_1[be]), 2))) + S1;
                S2 = 1 / (Math.pow(Math.abs(Lons[jj] - intArraymLon_1[be]), 2) +
                        Math.pow(Math.abs(Lats[jj] - intArraymLat_1[be]), 2)) + S2;
            }
            intArraymData_1[be] = S1 / S2;
        }

        Log.i("Condition", "3");

        ArrayList<LatLng> list = new ArrayList<LatLng>();

        // double[] intArraym1_1 = getIntent().getExtras().getDoubleArray("Data_Annaul_precip_Circ");

        final double[] Internsity = normArray1(intArraymData_1, getMin(intArraymData_1), getMax(intArraymData_1));
        final double[] Internsity2 = normArray2(intArraymData_1, getMin(intArraymData_1), getMax(intArraymData_1));
        //double[] Internsity2 = normArray1(InversX(intArraymData_1, getMax(intArraymData_1),getMin(intArraymData_1)),
        //  getMin(intArraymData_1), getMax(intArraymData_1));


        for (int ii = 0; ii < intArraymData_1.length; ii++) {

            double Rds1 = intArraymData_1[ii];


            //int Rds =Integer.parseInt(String.valueOf(Rds1));

            // PointTileOverlay pto = new PointTileOverlay();
            //pto.addPoint(new LatLng(Lats[ii], Lons[ii]));
            //getMap().addTileOverlay(new TileOverlayOptions().tileProvider(pto));


            final int finalIi = ii;


            final LatLng SYDNEY = new LatLng(intArraymLat_1[finalIi], intArraymLon_1[finalIi]);
            Circle amarker = mMap.addCircle(new CircleOptions()
                    .center(SYDNEY)
                    .radius(4000)
                    .strokeColor(Color.rgb((int) Internsity[finalIi], 0, (int) Internsity2[finalIi]))
                    .strokeWidth(4)
                    .strokeWidth(15)
                    .strokeColor(Color.rgb((int) Internsity[finalIi], 0, (int) Internsity2[finalIi]))
                    .fillColor(Color.rgb((int) Internsity[finalIi], 0, (int) Internsity2[finalIi]))
                    .clickable(true));

            amarker.setTag(String.format("%.2f", intArraymData_1[finalIi]));


        }

        Log.i("Condition", "4");

        LatLngBounds AUSTRALIA = new LatLngBounds(
                new LatLng(27.2724, 50.1), new LatLng(30.28, 52.93));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(AUSTRALIA.getCenter(), 7));
        //Gradient gradient = new Gradient(colors, startPoints);

        //mProvider = new HeatmapTileProvider.Builder()
        //    .data(list)
        //  .gradient(gradient)
        //  .build();

        perform_action(V1);
        MinmaxST = Getminmax(Internsity, Internsity2);


        TextView txtmin = (TextView) findViewById(R.id.Gradient_txtmin);
        TextView txtmax = (TextView) findViewById(R.id.Gradient_txtmax);

        Min = getMin(intArraymData_1);
        Max = getMax(intArraymData_1);

        if (Max == 0) {
            txtmax.setText("--");
            txtmin.setText(String.format("%.2f", Min) + "mm");
        } else {
            txtmax.setText(String.format("%.2f", Max) + "mm");
            txtmin.setText(String.format("%.2f", Min) + "mm");
        }


        final String[] date_string = new String[DateData.size() / 2];
        int u1 = 0;
        int u2 = (DateData.size() / 2) - 1;
        for (int bb = 0; bb < (DateData.size() / 2); bb++) {
            date_string[u2] = String.valueOf(DateData.get(u1)) + "/" + String.valueOf(DateData.get(u1 + 1));
            u2 = u2 - 1;
            u1 = u1 + 2;
        }


        Spinner spinData = (Spinner) findViewById(R.id.spinner);

        if (mapinit2 == 0) {
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, date_string);
            adapter.setDropDownViewResource(android.R.layout.
                    select_dialog_item);
            spinData.setAdapter(adapter);
            mapinit2 = 1;
        }

        Log.i("Condition", "5");

        //Year = String.valueOf(DateData.get(DateData.size()-2));
        //Month = String.valueOf(DateData.get(DateData.size()-1));

        Log.i("Postest", Year);
        Log.i("Postest", Month);

        //WWsitu[4] = Year;
        //WWsitu[5] = Month;
        //SharedPreferences shp = getSharedPreferences("text", MODE_PRIVATE);
        // shp.getString("Year", "1385");
        //shp.getString("Month", "1");
        //SharedPreferences.Editor shpE=shp.edit();

        /*SharedPreferences spy = getApplicationContext().getSharedPreferences("User",0);
        SharedPreferences.Editor editYM = spy.edit();
        editYM.putString("Year",String.valueOf(DateData.get(1)));
        editYM.putString("Tell",String.valueOf(DateData.get(2)));
        editYM.commit();*/


        //--------------------
        spinData.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int position, long id) {
                // TODO Auto-generated method stub
                if (!Gridshow2.this.isFinishing()){
                    Toast.makeText(Gridshow2.this, "انتخاب شما: " + date_string[position], Toast.LENGTH_SHORT).show();

                }


                    /*SharedPreferences spy = getApplicationContext().getSharedPreferences("User",0);
                    SharedPreferences.Editor editYM = spy.edit();
                    editYM.putString("Year",String.valueOf(DateData.get(position)));
                    editYM.putString("Tell",String.valueOf(DateData.get(position)));
                    editYM.commit();*/
                Log.i("Postest", String.valueOf(position));
                Log.i("Postest", String.valueOf(position2));

                if (position != position2) {
                    position2 = position;

                    Log.i("Postest", String.valueOf(position));
                    Log.i("Postest", String.valueOf(position2));
                    Year = String.valueOf(DateData.get(DateData.size() - (position + 2)));
                    Month = String.valueOf(DateData.get(DateData.size() - (position + 1)));

                    WWsitu[4] = Year;
                    WWsitu[5] = Month;

                    Log.i("Postest", Year);
                    Log.i("Postest", Month);

                    mapinit = 0;
                    doOnMap();
                    //Intent intent = new Intent(Gridshow2.this, Main2Activity.class);
                    //intent.putExtra("WhichWin2", WWsitu);
                    //intent.putExtra("DateCond", DateData);
                    //startActivity(intent);
                    Log.i("Condition", "6");

                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

                if (!Gridshow2.this.isFinishing()) {
                    Toast.makeText(Gridshow2.this, "عدم انتخاب", Toast.LENGTH_SHORT).show();
                }
                // TODO Auto-generated method stub

            }
        });


        mMap.setOnCircleClickListener(new GoogleMap.OnCircleClickListener() {

            @Override
            public void onCircleClick(Circle circle) {
                // Flip the r, g and b components of the circle's
                // stroke color.
                int strokeColor = circle.getStrokeColor() ^ 0x00ffffff;
                circle.setStrokeColor(strokeColor);
                String Str1 = (String) circle.getTag();

                Toast.makeText(Gridshow2.this, "بارش نقطه برابر با: " + Str1,
                        Toast.LENGTH_SHORT).show();


            }
        });

    }


    public void plot_Annual_Circl(final String Year, String Month, final String[] WWsitu) {


        AsyncHttpPost post = new AsyncHttpPost(
                "http://zimascience.com/Zima_Dr/W_water_Circe.php"
        );

        post.setTimeout(5000);

        MultipartFormDataBody body = new MultipartFormDataBody();

        //body.addStringPart("City","all");
        body.addStringPart("Year", Year);
        body.addStringPart("Tbname", WWsitu[1] + WWsitu[2]);
        body.addStringPart("Month", Month);

        post.setBody(body);

        AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
            @Override
            public void onCompleted(final Exception e, AsyncHttpResponse source, final String result) {

                if (e != null) {

                    Gridshow2.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            if (!Gridshow2.this.isFinishing()) {
                                Toast.makeText(Gridshow2.this, "خطا در برقراري اتصال با سرور !", Toast.LENGTH_LONG).show();
                                e.printStackTrace();
                            }
                        }
                    });

                }


                if (!result.equals("")) {

                    Log.i("Hash1", "Result created");

                    Gridshow2.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            //hash_All.clear();

                            try {

                                JSONArray jsonArray = new JSONArray(result);

                                Log.i("Hash2", result);
                                StringBuilder SbYear = new StringBuilder();


                                Log.i("Hash1", "Try created");
                                //Log.i("Hash2",result);

                                String[] intArray = new String[jsonArray.length()];

                                String[] resultingArray = jsonArray.join(",").split(",");

                                StringBuilder sbCirc = new StringBuilder();

                                for (int i = 0; i < jsonArray.length(); i++) {
                                    Log.i("Hash1", "for created");

                                    String name = jsonArray.getJSONObject(i).getString("Year");
                                    Log.i("Hash2", name);
                                    intArray[i] = name;

                                    Log.i("Hash2", String.valueOf(intArray[i]));
                                    JSONObject object = jsonArray.getJSONObject(i);


                                    Log.i("Hash1", "object created");
                                    HashMap<String, Object> hash_add = new HashMap<String, Object>();


                                    hash_add.put("Year", object.get("Year"));
                                    String[] Valus = new String[30];
                                    for (int kk = 1; kk < 29; kk++) {

                                        sbCirc.append(object.get("St" + kk));
                                        sbCirc.append(",");

                                    }


                                }

                                String stringArrayM = String.valueOf(sbCirc);

                                String[] stringArrayM2 = stringArrayM.split(",");


                                for (int i = 0; i < stringArrayM2.length; i++) {

                                    String name = stringArrayM2[i];
                                    Log.i("Hash22", name);
                                    double d = Double.parseDouble(name);

                                    intArraym1[i] = d;

                                }


                                //Toast.makeText(Gridshow2.this, "نتايج جمع آوري شد !", Toast.LENGTH_LONG).show();

                                final ArrayList<Integer> DateData = new ArrayList<>(getIntent().getExtras().getIntegerArrayList("DateCond"));
                                final ArrayList<String> DateLatLon = new ArrayList<>(getIntent().getExtras().getStringArrayList("LatLongrid"));

                                //int[] intArray = new int[stringArray.length];
                                Log.i("Hash2", "1 st");


                                //Log.i("Hash2", String.valueOf(returnArray));


                                Log.i("Hash2", "Sb went");


                                // Intent intent = new Intent(St_Annual_Circ1.this,Forecasting.class);
                                //intent.putExtra("Data", (Serializable) sb);
                                // intent.putExtra("DataMY", (Serializable) sbM);
                                // startActivity(intent);


                            } catch (Exception e) {
                                //Toast.makeText(Gridshow2.this, "نتايج جمع آوري نشد !", Toast.LENGTH_LONG).show();
                                // Log.i("Hash1","erro after try created");
                                e.printStackTrace();
                                Log.e("Hash2", "error is: ", e);
                            }


                        }
                    });

                }

            }
        });


    }


    public double[] InversX(double[] inpArray, double max, double min) {

        double[] Rds2int = new double[inpArray.length];
        for (int ii = 0; ii < inpArray.length; ii++) {
            Rds2int[ii] = (255 - 0) * (inpArray[ii] - max) / (max - min) + 0;
            Log.i("Inversed1", String.valueOf(Rds2int[ii]) + "--" + inpArray[ii]);

        }

        return Rds2int;
    }


    public double[] normArray1(double[] inpArray, double min, double max) {

        double[] Rds1int = new double[inpArray.length];

        for (int ii = 0; ii < inpArray.length; ii++) {

            double Rds1 = inpArray[ii];

            Rds1int[ii] = (255 - 0) * (inpArray[ii] - min) / ((max + 1) - min) + 0;
            Log.i("Inversed", String.valueOf(Rds1int[ii]) + "--" + inpArray[ii]);
        }

        return Rds1int;
    }


    public double[] normArray2(double[] inpArray, double min, double max) {
        int Coef = 0;
        if (max == 0)
            Coef = 255;
        else
            Coef = 0;

        double[] Rds1int = new double[inpArray.length];

        for (int ii = 0; ii < inpArray.length; ii++) {

            double Rds1 = inpArray[ii];

            Rds1int[ii] = Math.abs((255 - 0) * (inpArray[ii] - max) / ((max + 1) - min) + Coef);
            Log.i("Inversed", String.valueOf(Rds1int[ii]) + "--" + inpArray[ii]);
        }

        return Rds1int;
    }


    public double[] Getminmax(double[] inpArray, double[] inpArray2) {
        double[] maxInts12 = new double[2];
        double maxints1 = getMax(inpArray);
        double maxints2 = getMax(inpArray2);
        maxInts12[0] = maxints1;
        maxInts12[1] = maxints2;
        return maxInts12;
    }


    public static double getMin(double[] array) {

        double min = array[0];
        for (int i = 1; i < array.length; i++) {
            min = Math.min(min, array[i]);
        }
        return min;
    }

    public static double getMax(double[] array) {

        double max = array[0];
        for (int i = 1; i < array.length; i++) {
            max = Math.max(max, array[i]);
        }
        return max;
    }


    public boolean onMarkerClick(final Marker Station) {

        // Retrieve the data from the marker.
        String clickStName = (String) Station.getTag();

        // Check if a click count was set, then display the click count.
        if (clickStName != null) {

            //Intent intent = new Intent(Gridshow2.this,wAnnaul_Data.class);
            //intent.putExtra("Station_name_annaul",clickStName);
            //startActivity(intent);


            //clickCount = clickCount + 1;
            //marker.setTag(clickCount);


            //Toast.makeText(this,
            //marker.getTitle() +
            //     " has been clicked " + clickCount + " times.",
            //Toast.LENGTH_SHORT).show();


        }


        Toast.makeText(this,
                "No work!",
                Toast.LENGTH_SHORT).show();

        // Return false to indicate that we have not consumed the event and that we wish
        // for the default behavior to occur (which is for the camera to move such that the
        // marker is centered and for the marker's info window to open, if it has one).
        return false;
    }


    @SuppressLint("NewApi")
    public void perform_action(View v) {
        TextView btn = (TextView) findViewById(R.id.Gradient_map2);

        //Color.parseColor() method allow us to convert
        // a hexadecimal color string to an integer value (int color)
        //int[] colors = {Color.parseColor("#008000"),Color.parseColor("#ADFF2F")};

        //create a new gradient color
        //GradientDrawable gd = new GradientDrawable(
        //GradientDrawable.Orientation.TOP_BOTTOM, colors);

        GradientDrawable gd = new GradientDrawable();
        gd.setColors(new int[]{
                Color.rgb(0, 0, 255), // green
                Color.rgb(255, 0, 0) // green
                // green

        });


        gd.setGradientType(GradientDrawable.LINEAR_GRADIENT);
        gd.setOrientation(GradientDrawable.Orientation.LEFT_RIGHT);

        // Set GradientDrawable shape is a rectangle
        gd.setShape(GradientDrawable.RECTANGLE);

        // Set 3 pixels width solid blue color border
        gd.setStroke(3, Color.BLUE);

        // Set GradientDrawable width and in pixels
        gd.setSize(450, 150);


        gd.setCornerRadius(1f);
        //apply the button background to newly created drawable gradient
        btn.setBackground(gd);
    }


}
