Newer
Older
NemophilaClient / app / src / main / java / com / example / nemophila / PostActivity.java
package com.example.nemophila;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;


import com.example.nemophila.entities.Account;
import com.example.nemophila.entities.Shop;
import com.example.nemophila.viewmodels.PostsViewModel;
import com.example.nemophila.viewmodels.ShopsViewModel;
import com.google.android.material.snackbar.Snackbar;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import retrofit2.Retrofit;


public class PostActivity extends AppCompatActivity {
    private String pid;
    private String uid;
    private String name;
    private String genre;
    private int rate;
    private String comment;
    private String token;
    private String sid;
    private String[] img;
    private String shopName;
    private ImageButton[] deleteButtons;
    private ImageView[] postImages;
    private List<Uri> uriLists = new ArrayList<Uri>(3);

    private PostsViewModel postsViewModel;
    private ShopsViewModel shopsViewModel;
    private Nemophila nemophila;

    //画像挿入ランチャー起動
    private ActivityResultLauncher<String[]> launcher = registerForActivityResult(new ActivityResultContracts.OpenDocument(), new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {

            uriLists.add(uri);
            System.out.println("登録された画像数:"+uriLists.size());

            postImages[uriLists.size()-1].setImageURI(uriLists.get(uriLists.size()-1));
            deleteButtons[uriLists.size()-1].setVisibility(View.VISIBLE);
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        Shop shop;
        nemophila = (Nemophila) this.getApplication();
        postsViewModel = new ViewModelProvider(this).get(PostsViewModel.class);
        shopsViewModel = new ViewModelProvider(this).get(ShopsViewModel.class);

        img = new String[3];
        deleteButtons = new ImageButton[3];
        postImages = new ImageView[3];

//店舗新規作成のオブザーバー
        shopsViewModel.getCurrentLiveData().observe(this, new Observer<Shop>() {
            @Override
            public void onChanged(Shop shop) {
                System.out.println("店舗新規作成完了");
                postsViewModel.createPost(uid, token, shop.getSid(), rate, genre, comment, img[0], img[1], img[2]);

                System.out.println("lat" + nemophila.getCurrentLatitude() + "\nlong" + nemophila.getCurrentLongitude());

                //投稿時にリセット
                nemophila.setDummyShop(null);
                nemophila.setCurrentShop(null);

                Intent intent = new Intent(getApplication(), MapsActivity.class);
                startActivity(intent);
            }
        });

        uid = nemophila.getUid();
        token = nemophila.getToken();
        shop = nemophila.getCurrentShop();

        if (shop == null){
            Shop dummyShop = nemophila.getDummyShop();
            sid = dummyShop.getSid();
            shopName = dummyShop.getName();
        }else{
            sid = shop.getSid();
            shopName = shop.getName();
        }

        //店名を表示
        TextView textView = findViewById(R.id.shopNamePoatAc);
        textView.setText(shopName);

        //左上のボタンでキャンセル(ShopActivityに戻る)
        //確認用ダイアログを入れたい
        Button returnButton = (Button)findViewById(R.id.postAcReturnButton);
        returnButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                //キャンセル時にリセット
                nemophila.setDummyShop(null);
                nemophila.setCurrentShop(null);
                //画面遷移
                Intent intent = new Intent(getApplication(), MapsActivity.class);
                startActivity(intent);
            }
        });

        //評価を入力するためのレーティングバー
        RatingBar ratingBar = findViewById(R.id.ratingBar);
        //評価が入力された時の処理
        ratingBar.setOnRatingBarChangeListener((inputRate,gettingrate,fromUser) -> {
            rate = (int)gettingrate;
        });

        ArrayAdapter<String> genreAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        genreAdapter.add("ジャンルを選択");
        genreAdapter.add("和食");
        genreAdapter.add("洋食");
        genreAdapter.add("中華");
        genreAdapter.add("イタリアン");
        genreAdapter.add("フレンチ");
        genreAdapter.add("その他海外料理");
        genreAdapter.add("カフェ");
        genreAdapter.add("バー");
        genreAdapter.add("居酒屋");
        genreAdapter.add("焼肉");
        genreAdapter.add("鍋");
        genreAdapter.add("カレー");
        genreAdapter.add("丼");
        genreAdapter.add("ラーメン");
        genreAdapter.add("うどん");
        genreAdapter.add("そば");
        genreAdapter.add("その他");
        Spinner genreSpinner = (Spinner) findViewById(R.id.inputGenre);
        genreSpinner.setAdapter(genreAdapter);

        genreSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            //ジャンルプルダウンで選択が何もなかった時の動作
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}

            //ジャンルプルダウンで何か選択された時の動作
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                genre = (String) genreSpinner.getSelectedItem();
                if (genre.equals("ジャンルを選択")){
                    genre = null;
                }
            }
        });

//        投稿画像
        postImages[0] = findViewById(R.id.imageView1);
        postImages[1] = findViewById(R.id.imageView2);
        postImages[2] = findViewById(R.id.imageView3);

        ImageButton selectPictureButton = (ImageButton) findViewById(R.id.selectpicturebutton);
        selectPictureButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                if (uriLists.size() < 3) {
//                画像選択(Max3枚)
                    launcher.launch(new String[]{"image/*"});
                }else{
                    Snackbar.make(v, "選択できる画像は最大で3枚です。", Snackbar.LENGTH_SHORT).show();
                }
            }
        });

//        写真の削除ボタン
        deleteButtons[0]= (ImageButton) findViewById(R.id.deleteButton1);
        deleteButtons[1]= (ImageButton) findViewById(R.id.deleteButton2);
        deleteButtons[2]= (ImageButton) findViewById(R.id.deleteButton3);

        deleteButtons[0].setVisibility(View.INVISIBLE);
        deleteButtons[1].setVisibility(View.INVISIBLE);
        deleteButtons[2].setVisibility(View.INVISIBLE);

//        ボタン1
        deleteButtons[0].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("削除ボタン1");
                uriLists.remove(0);
                System.out.println("urilist要素数" +uriLists.size());
                if (uriLists.size() == 0){
                    postImages[0].setImageURI(null);
                    deleteButtons[0].setVisibility(View.INVISIBLE);
                }else {
                    for (int i = 0; i < uriLists.size(); i++) {
                        postImages[i].setImageURI(uriLists.get(i));
                        postImages[uriLists.size()].setImageURI(null);
                        deleteButtons[uriLists.size()].setVisibility(View.INVISIBLE);
                    }
                }
            }
        });
//        ボタン2
        deleteButtons[1].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("削除ボタン2");
                uriLists.remove(1);
                System.out.println("urilist要素数" + uriLists.size());
                for (int i = 0; i < uriLists.size(); i++) {
                    postImages[i].setImageURI(uriLists.get(i));
                    postImages[uriLists.size()].setImageURI(null);
                    deleteButtons[uriLists.size()].setVisibility(View.INVISIBLE);
                }
            }
        });

//        ボタン3
        deleteButtons[2].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("削除ボタン3");
                uriLists.remove(2);
                System.out.println("urilist要素数" +uriLists.size());
                for (int i = 0; i < uriLists.size(); i++) {
                    postImages[i].setImageURI(uriLists.get(i));
                    postImages[uriLists.size()].setImageURI(null);
                    deleteButtons[uriLists.size()].setVisibility(View.INVISIBLE);
                }
            }
        });

        //投稿ボタンの処理
        Button postButton = (Button)findViewById(R.id.postButton);
        postButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                postButton.setEnabled(false);
                System.out.println("投稿ボタンのクリック");

                EditText editComment = (EditText) findViewById(R.id.inputComment);
                comment = editComment.getText().toString();

                //評価とジャンルが入力済の時
                if(rate != 0 && genre != null) {
                    //画像をエンコードしてサーバーに送る処理
                    for (int i = 0; i < uriLists.size(); i++) {
                        try {
                            InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(uriLists.get(i));
                            Bitmap bitmap = BitmapFactory.decodeStream(new BufferedInputStream(inputStream));
                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                            byte[] byteArray = stream.toByteArray();
                            String encoded = Base64.getEncoder().encodeToString(byteArray);
                            img[i] = encoded;

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            postButton.setEnabled(true);
                        }
                    }

                    if (shop == null) {
                        //新規店舗に投稿
                        shopsViewModel.createShop(shopName, nemophila.getCurrentLongitude(), nemophila.getCurrentLatitude());
                    } else {
                        //既存店舗に投稿
                        postsViewModel.createPost(uid, token, sid, rate, genre, comment, img[0], img[1], img[2]);
                        System.out.println("既存店舗に投稿");
                        System.out.println("lat" + nemophila.getCurrentLatitude() + "\nlong" + nemophila.getCurrentLongitude());

                        //投稿時にリセット
                        nemophila.setDummyShop(null);
                        nemophila.setCurrentShop(null);

                        Intent intent = new Intent(getApplication(), MapsActivity.class);
                        startActivity(intent);
                    }
                }else if(rate == 0) {
                    //評価未入力
                    System.out.println("評価未設定クリック");
                    Snackbar.make(v, "評価を選択してください", Snackbar.LENGTH_SHORT).show();
                    postButton.setEnabled(true);
                }else if (genre == null){
                    //ジャンル未入力
                    System.out.println("ジャンル未設定クリック");
                    Snackbar.make(v, "ジャンルを選択してください", Snackbar.LENGTH_SHORT).show();
                    postButton.setEnabled(true);
                }
            }
        });
    }
}