diff --git a/android-app/app/src/main/AndroidManifest.xml b/android-app/app/src/main/AndroidManifest.xml index d9afe3d..9d069e5 100644 --- a/android-app/app/src/main/AndroidManifest.xml +++ b/android-app/app/src/main/AndroidManifest.xml @@ -70,6 +70,10 @@ + + + + commentList = new ArrayList<>(); + TextView CommentCount; + RecyclerView mCommentsRecycler; + private FirebaseFirestore mFirestore; + private FirebaseUser mCurrentUser; + private CircleImageView user_image; + private MaterialFavoriteButton sav_button, like_btn; + private FrameLayout pager_layout; + private RelativeLayout indicator_holder; + private ViewPager pager; + private RichEditor mCommentText; + private DotsIndicator indicator2; + private CommentsAdapter mAdapter; + TextView p_nameTV, p_instTV, timestampTV; + boolean approved = true; + boolean alreadyLiked; + FrameLayout mImageholder; + LinearLayout adminActivity; + View vBgLike; + ImageView ivLike; + @SuppressLint({"SetTextI18n", "RtlHardcoded"}) + @Override + protected void onCreate(Bundle savedInstanceState) { + requestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS); + getWindow().setEnterTransition(new Explode()); + getWindow().setExitTransition(new Explode()); + + super.onCreate(savedInstanceState); + SharedPreferences sharedPreferences = getSharedPreferences("Theme", Context.MODE_PRIVATE); + String themeName = sharedPreferences.getString("ThemeName", "Default"); + if (themeName.equalsIgnoreCase("TealTheme")) { + setTheme(R.style.TealTheme); + } else if (themeName.equalsIgnoreCase("VioleteTheme")) { + setTheme(R.style.VioleteTheme); + } else if (themeName.equalsIgnoreCase("PinkTheme")) { + setTheme(R.style.PinkTheme); + } else if (themeName.equalsIgnoreCase("DelRio")) { + setTheme(R.style.DelRio); + } else if (themeName.equalsIgnoreCase("DarkTheme")) { + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); + setTheme(R.style.Dark); + } else if (themeName.equalsIgnoreCase("Lynch")) { + setTheme(R.style.Lynch); + } else { + setTheme(R.style.AppTheme); + } + setContentView(R.layout.activity_post_comments); + mFirestore = FirebaseFirestore.getInstance(); + mCurrentUser = FirebaseAuth.getInstance().getCurrentUser(); + userId=FirebaseAuth.getInstance().getCurrentUser().getUid(); + user_image = findViewById(R.id.comment_admin); + post_desc = findViewById(R.id.comment_post_desc); + p_nameTV = findViewById(R.id.post_username); + p_instTV = findViewById(R.id.dept_institute); + postDb = FirebaseFirestore.getInstance().collection("Issues"); + timestampTV = findViewById(R.id.post_timestamp); + likeCount = findViewById(R.id.like_count); + saveCount = findViewById(R.id.save_count); + CommentCount = findViewById(R.id.textView8); + mCommentsRecycler = findViewById(R.id.coments); + adminActivity = findViewById(R.id.adminActivity); + like_btn = findViewById(R.id.like_button); + vBgLike = findViewById(R.id.vBgLike); + ivLike = findViewById(R.id.ivLike); + pager = findViewById(R.id.pager); + pager_layout = findViewById(R.id.pager_layout); + sav_button = findViewById(R.id.save_button); + me = new UserRepository(getApplication()).getStaticUser(); + mImageholder = findViewById(R.id.image_holder); + indicator2 = findViewById(R.id.indicator); + indicator_holder = findViewById(R.id.indicator_holder); + + + approved = getIntent().getBooleanExtra("approveStatus", true); + alreadyLiked = getIntent().getBooleanExtra("alreadyLiked", false); + + + + post = (Post) getIntent().getSerializableExtra("post"); + if(userId==null) finish(); + if(post != null) { + setUpData(post); + }else{ + ProgressDialog mDialog = new ProgressDialog(this); + mDialog.setMessage("Please wait. Loading post..."); + mDialog.setIndeterminate(true); + mDialog.setCanceledOnTouchOutside(false); + mDialog.setCancelable(false); + mDialog.show(); + String link = getIntent().getData().toString(); + String id = link.substring(link.lastIndexOf("/") + 1); + + FirebaseFirestore.getInstance().collection("Posts") + .document(id) + .get() + .addOnSuccessListener(documentSnapshot -> { + mDialog.dismiss(); + try { + post = documentSnapshot.toObject(Post.class); + if(post!=null) setUpData(post); + else{ + Log.d("ErrorPost", id); + Toast.makeText(this, "Error Post", Toast.LENGTH_SHORT).show(); + finish(); + } + }catch (Exception a){ + Log.d("ErrorPost", a.getLocalizedMessage()); + Toast.makeText(this, "Error Post", Toast.LENGTH_SHORT).show(); + finish(); + } + }).addOnFailureListener(e -> { + mDialog.dismiss(); + Toast.makeText(IssuesDetailsActivity.this, "Post not found", Toast.LENGTH_SHORT).show(); + finish(); + }); + } + } + + @SuppressLint("SetTextI18n") + void setUpData(Post post){ + if (!approved && ADMIN_UID_LIST.contains(userId)) { + Toast.makeText(this, "Approve or Delete this Post", Toast.LENGTH_SHORT).show(); + adminActivity.setVisibility(View.VISIBLE); + findViewById(R.id.approvePost).setOnClickListener(view -> approvePost(post)); + findViewById(R.id.deletePost).setOnClickListener(view -> deletePost(post.getPostId())); + } else { + adminActivity.setVisibility(View.GONE); + } + + if (post.getImage_count() > 0) { + mImageholder.setVisibility(View.VISIBLE); + } else { + mImageholder.setVisibility(View.GONE); + } + + + user_id = post.getUserId(); + post_desc.setDisplayText(post.getDescription()); + // p_instTV.setText(post.getDept() + ", " + post.getInstitute()); + + + try { + if (post.getInstitute() == null) { + p_instTV.setText(post.getDept()); + } else if (post.getDept() == null) { + p_instTV.setText(post.getInstitute()); + } else { + p_instTV.setText(post.getDept() + ", " + post.getInstitute()); + } + }catch (Exception j){ + p_instTV.setText(post.getDept()); + } + + p_nameTV.setText(post.getName()); + timestampTV.setText(TimeAgo.using(Long.parseLong(Objects.requireNonNull(post.getTimestamp())))); + setupCommentView(); + getLikeandFav(post); + setStatData(post); + + likeCount.setOnClickListener(view -> view.getContext().startActivity(new Intent(view.getContext(), WhoLikedActivity.class).putExtra("postId", post.getPostId()).putExtra("type", "Liked_Users"))); + + + + mCommentText = findViewById(R.id.text); + mCommentText.setPlaceholder("Type your comment here..."); + ImageView mCommentsSend = findViewById(R.id.send); + mProgress = findViewById(R.id.progressBar5); + + myImage = findViewById(R.id.imageView7); + + commentList = new ArrayList<>(); + mAdapter = new CommentsAdapter(commentList, this, owner, post.getComment_count()); + mCommentsSend.setOnClickListener(view -> { + String comment = mCommentText.getHtml(); + if (!TextUtils.isEmpty(comment)) + sendComment(comment, mProgress); + else + AnimationUtil.shakeView(mCommentText, IssuesDetailsActivity.this); + }); + + mCommentsRecycler.setItemAnimator(new DefaultItemAnimator()); + mCommentsRecycler.setLayoutManager(new LinearLayoutManager(this)); + mCommentsRecycler.setHasFixedSize(true); + mCommentsRecycler.setAdapter(mAdapter); + + getComments(mProgress); + + Glide.with(getApplicationContext()) + .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) + .load(me.getImage()) + .into(myImage); + } + + private void approvePost(Post post) { + post.setLike_count(0); + final ProgressDialog mDialog = new ProgressDialog(this); + mDialog.setMessage("Approving..."); + mDialog.setIndeterminate(true); + mDialog.setCancelable(false); + mDialog.setCanceledOnTouchOutside(false); + mDialog.show(); + postDb + .document(post.getPostId()) + .set(post).addOnSuccessListener(aVoid -> { + addToNotification("An Admin Approved Your Post", "post"); + mFirestore.collection("PendingPosts") + .document(post.getPostId()).delete(); + mDialog.dismiss(); + Toasty.success(getApplicationContext(), "Approved", Toasty.LENGTH_SHORT, true).show(); + finish(); + }); + + } + + private void deletePost(String Id) { + final ProgressDialog mDialog = new ProgressDialog(this); + mDialog.setMessage("Removing from Approval List..."); + mDialog.setIndeterminate(true); + mDialog.setCancelable(false); + mDialog.setCanceledOnTouchOutside(false); + mDialog.show(); + mFirestore.collection("PendingPosts") + .document(Id).delete().addOnSuccessListener(aVoid -> { + addToNotification("An Admin Deleted Your Post, Try posting good contents only.", ""); + mDialog.dismiss(); + Toasty.success(getApplicationContext(), "Done", Toasty.LENGTH_SHORT, true).show(); + finish(); + }); + } + + + @SuppressLint("SetTextI18n") + private void setupCommentView() { + if (post.getImage_count() == 0) { + pager_layout.setVisibility(View.GONE); + } else if (post.getImage_count() == 1) { + pager_layout.setVisibility(View.VISIBLE); + ArrayList multipleImages = new ArrayList<>(); + PostPhotosAdapter photosAdapter = new PostPhotosAdapter(Home.context, this, multipleImages, false, post.getPostId(), like_btn, post.getUserId(), true); + setUrls(multipleImages, photosAdapter, post); + pager.setAdapter(photosAdapter); + indicator_holder.setVisibility(View.GONE); + photosAdapter.notifyDataSetChanged(); + pager_layout.setVisibility(View.VISIBLE); + } else { + ArrayList multipleImages = new ArrayList<>(); + PostPhotosAdapter photosAdapter = new PostPhotosAdapter(Home.context, this, multipleImages, false, post.getPostId(), like_btn, post.getUserId(), true); + setUrls(multipleImages, photosAdapter, post); + + pager.setAdapter(photosAdapter); + photosAdapter.notifyDataSetChanged(); + indicator2.setDotsClickable(true); + indicator2.setViewPager(pager); + + final Handler handler = new Handler(); + final Runnable slide = () -> { + if (pager.getCurrentItem() == multipleImages.size()) { + pager.setCurrentItem(0, true); + return; + } + pager.setCurrentItem(pager.getCurrentItem() + 1, true); + }; + Timer slideTimer = new Timer(); + slideTimer.schedule(new TimerTask() { + @Override + public void run() { + handler.post(slide); + } + }, 3000, 3000); + + pager_layout.setVisibility(View.VISIBLE); + indicator_holder.setVisibility(View.VISIBLE); + } + + mFirestore.collection("Users") + .document(user_id) + .get() + .addOnSuccessListener(documentSnapshot -> Glide.with(getApplicationContext()) + .setDefaultRequestOptions(new RequestOptions().placeholder(R.drawable.logo_round)) + .load(documentSnapshot.getString("image")) + .into(user_image)) + .addOnFailureListener(e -> Log.e("error", e.getLocalizedMessage())); + p_nameTV.setOnClickListener(view -> { + startActivity(new Intent(getApplicationContext(), FriendProfile.class).putExtra("f_id", post.getUserId())); + }); + p_instTV.setOnClickListener(view -> { + startActivity(new Intent(getApplicationContext(), FriendProfile.class).putExtra("f_id", post.getUserId())); + }); + + } + + @Override + public void finish() { + super.finish(); + overridePendingTransitionExit(); + } + + @Override + public void startActivity(Intent intent) { + super.startActivity(intent); + overridePendingTransitionEnter(); + } + + protected void overridePendingTransitionEnter() { + overridePendingTransition(R.anim.slide_from_right, R.anim.slide_to_left); + } + + protected void overridePendingTransitionExit() { + overridePendingTransition(R.anim.slide_from_left, R.anim.slide_to_right); + } + + private void setUrls(ArrayList multipleImages, PostPhotosAdapter photosAdapter, Post post) { + String url0, url1, url2, url3, url4, url5, url6; + + url0 = post.getImage_url_0(); + url1 = post.getImage_url_1(); + url2 = post.getImage_url_2(); + url3 = post.getImage_url_3(); + url4 = post.getImage_url_4(); + url5 = post.getImage_url_5(); + url6 = post.getImage_url_6(); + + if (!TextUtils.isEmpty(url0)) { + MultipleImage image = new MultipleImage(url0); + multipleImages.add(image); + photosAdapter.notifyDataSetChanged(); + Log.i("url0", url0); + } + + if (!TextUtils.isEmpty(url1)) { + MultipleImage image = new MultipleImage(url1); + multipleImages.add(image); + photosAdapter.notifyDataSetChanged(); + Log.i("url1", url1); + } + + if (!TextUtils.isEmpty(url2)) { + MultipleImage image = new MultipleImage(url2); + multipleImages.add(image); + photosAdapter.notifyDataSetChanged(); + Log.i("url2", url2); + } + + if (!TextUtils.isEmpty(url3)) { + MultipleImage image = new MultipleImage(url3); + multipleImages.add(image); + photosAdapter.notifyDataSetChanged(); + Log.i("url3", url3); + } + + if (!TextUtils.isEmpty(url4)) { + MultipleImage image = new MultipleImage(url4); + multipleImages.add(image); + photosAdapter.notifyDataSetChanged(); + Log.i("url4", url4); + } + + if (!TextUtils.isEmpty(url5)) { + MultipleImage image = new MultipleImage(url5); + multipleImages.add(image); + photosAdapter.notifyDataSetChanged(); + Log.i("url5", url5); + } + + if (!TextUtils.isEmpty(url6)) { + MultipleImage image = new MultipleImage(url6); + multipleImages.add(image); + photosAdapter.notifyDataSetChanged(); + Log.i("ur6", url6); + } + + + } + + public boolean isOnline() { + ConnectivityManager cm = + (ConnectivityManager) Home.context.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo netInfo = cm.getActiveNetworkInfo(); + return netInfo != null && netInfo.isConnectedOrConnecting(); + } + + private void getLikeandFav(Post post) { + like_btn.setFavorite(alreadyLiked); + like_btn.setOnFavoriteChangeListener((buttonView, favorite) -> { + updateLike(post.getPostId()); + }); + + + try { + postDb.document(post.getPostId()) + .collection("Saved_Users") + .document(mCurrentUser.getUid()) + .get() + .addOnSuccessListener(documentSnapshot -> { + + if (documentSnapshot.exists()) { + boolean fav = documentSnapshot.getBoolean("Saved"); + + sav_button.setFavorite(fav, false); + } else { + Log.e("Fav", "No document found"); + + } + + if (isOnline()) { + sav_button.setOnFavoriteChangeListener((buttonView, favorite) -> { + Map favMap = new HashMap<>(); + if (favorite) { + favMap.put("Saved", true); + + try { + + mFirestore.collection("Posts") + .document(post.getPostId()) + .collection("Saved_Users") + .document(mCurrentUser.getUid()) + .set(favMap) + .addOnSuccessListener(aVoid -> { + saveCo++; + saveCount.setText(String.valueOf(saveCo)); + + Map postMap = new HashMap<>(); + postMap.put("postId", post.getPostId()); + postMap.put("userId", post.getUserId()); + postMap.put("name", post.getName()); + postMap.put("username", post.getUsername()); + postMap.put("institute", post.getInstitute()); + postMap.put("dept", post.getDept()); + postMap.put("timestamp", post.getTimestamp()); + postMap.put("image_count", post.getImage_count()); + postMap.put("description", post.getDescription()); + + try { + postMap.put("image_url_0", post.getImage_url_0()); + } catch (Exception e) { + e.printStackTrace(); + } + try { + postMap.put("image_url_1", post.getImage_url_1()); + } catch (Exception e) { + e.printStackTrace(); + } + try { + postMap.put("image_url_2", post.getImage_url_2()); + } catch (Exception e) { + e.printStackTrace(); + } + try { + postMap.put("image_url_3", post.getImage_url_3()); + } catch (Exception e) { + e.printStackTrace(); + } + try { + postMap.put("image_url_4", post.getImage_url_4()); + } catch (Exception e) { + e.printStackTrace(); + } + try { + postMap.put("image_url_5", post.getImage_url_5()); + } catch (Exception e) { + e.printStackTrace(); + } + try { + postMap.put("image_url_6", post.getImage_url_6()); + } catch (Exception e) { + e.printStackTrace(); + } + + mFirestore.collection("Users") + .document(mCurrentUser.getUid()) + .collection("Saved_Posts") + .document(post.getPostId()) + .set(postMap) + .addOnSuccessListener(aVoid12 -> { + // Toast.makeText(context, "Added to Saved_Posts, post '" + post.postId, Toast.LENGTH_SHORT).show(); + }).addOnFailureListener(e -> Log.e("Error add fav", e.getMessage())); + }) + .addOnFailureListener(e -> Log.e("Error fav", e.getMessage())); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + favMap.put("Saved", false); + try { + mFirestore.collection("Posts") + .document(post.getPostId()) + .collection("Saved_Users") + .document(mCurrentUser.getUid()) + //.set(favMap) + .delete() + .addOnSuccessListener(aVoid -> { + saveCo--; + saveCount.setText(String.valueOf(saveCo)); + mFirestore.collection("Users") + .document(mCurrentUser.getUid()) + .collection("Saved_Posts") + .document(post.getPostId()) + .delete() + .addOnSuccessListener(aVoid1 -> { + // Toast.makeText(context, "Removed from Saved_Posts, post '" + post.postId, Toast.LENGTH_SHORT).show(); + }) + .addOnFailureListener(e -> Log.e("Error remove fav", e.getMessage())); + + }) + .addOnFailureListener(e -> Log.e("Error fav", e.getMessage())); + + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + }) + .addOnFailureListener(e -> Log.e("Error Fav", e.getMessage())); + } catch (NullPointerException ignored) { + } + } + + @SuppressLint("SetTextI18n") + void setStatData(Post post) { + likeCount.setText(String.valueOf(post.getLiked_count())); + } + + @SuppressLint("SetTextI18n") + public void updateLike(String postId) { + int postLikes = post.getLiked_count(); + if(!alreadyLiked){ + postLikes++; + try { + Map likeMap = new HashMap<>(); + likeMap.put("liked", true); + postDb.document(postId) + .collection("Liked_Users") + .document(mCurrentUser.getUid()) + .set(likeMap) + .addOnSuccessListener(aVoid -> { + alreadyLiked=true; + addToNotification("Liked your post", "like"); + }) + .addOnFailureListener(e -> Log.e("Error like", e.getMessage())); + } catch (Exception ignored) { + } + }else{ + postLikes--; + try { + mFirestore.collection("Posts") + .document(postId) + .collection("Liked_Users") + .document(mCurrentUser.getUid()) + //.set(likeMap) + .delete() + .addOnSuccessListener(aVoid -> { + alreadyLiked=true; + //holder.like_count.setText(String.valueOf(Integer.parseInt(holder.like_count.getText().toString())-1)); + //Toast.makeText(context, "Unliked post '" + post.postId, Toast.LENGTH_SHORT).show(); + }) + .addOnFailureListener(e -> Log.e("Error unlike", e.getMessage())); + } catch (Exception ignored) { + } + } + likeCount.setText(String.valueOf(postLikes)); + HashMap scoreMap = new HashMap<>(); + scoreMap.put("liked_count", postLikes); + mFirestore + .collection("Posts") + .document(postId) + .update(scoreMap).addOnSuccessListener(aVoid -> { + }); + } + + @SuppressLint("SetTextI18n") + public void updateComment() { + try { + int com_count = post.getComment_count()+1; + HashMap scoreMap = new HashMap<>(); + scoreMap.put("comment_count", com_count); + mFirestore.collection("Posts") + .document(post.getPostId()) + .update(scoreMap).addOnSuccessListener(aVoid -> { + CommentCount.setText(" "+com_count); + }); + } catch (NullPointerException ignored) { + + } + } + private void addToNotification(String message, String type) { + if (!post.getUserId().equals(me.getId())) { + Notification notification = new Notification(post.getPostId(),post.getUserId(), me.getName(), me.getImage(), message, String.valueOf(System.currentTimeMillis()), type, post.getPostId(), false); + mFirestore.collection("Users") + .document(post.getUserId()) + .collection("Info_Notifications") + .document(notification.getId()).set(notification) + .addOnSuccessListener(documentReference -> new SendNotificationAsyncTask(notification).execute()) + .addOnFailureListener(e -> Log.e("Error", e.getLocalizedMessage())); + } + } + + public void finishThis(View v) { + finish(); + overridePendingTransitionExit(); + } + + @SuppressLint("NotifyDataSetChanged") + private void sendComment(final String comment, final ProgressBar mProgress) { + mProgress.setVisibility(View.VISIBLE); + String commentId = getSaltString(); + Comment comment1 = new Comment(me.getId(), me.getName(), me.getImage(), post.getPostId(), comment, String.valueOf(System.currentTimeMillis()), commentId); + mCommentText.setHtml(""); + mFirestore.collection("Posts") + .document(post.getPostId()) + .collection("Comments") + .document(commentId) + .set(comment1) + .addOnSuccessListener(documentReference -> { + mProgress.setVisibility(View.GONE); + addToNotification("Commented on your post", "comment"); + updateComment(); + Toasty.success(IssuesDetailsActivity.this, "Comment added", Toasty.LENGTH_SHORT, true).show(); + mAdapter.notifyDataSetChanged(); + }) + .addOnFailureListener(e -> { + mCommentText.setHtml(comment1.getComment()); + mProgress.setVisibility(View.GONE); + Toasty.error(IssuesDetailsActivity.this, "Error adding comment: " + e.getMessage(), Toasty.LENGTH_SHORT, true).show(); + Log.e("Error sending comment", Objects.requireNonNull(e.getMessage())); + }); + + } + + + @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"}) + private void getComments(final ProgressBar mProgress) { + CommentCount.setText(" " + post.getComment_count()); + mProgress.setVisibility(View.VISIBLE); + mFirestore.collection("Posts") + .document(post.getPostId()) + .collection("Comments") + .orderBy("timestamp", Query.Direction.DESCENDING).limit(15) + .addSnapshotListener(this, (querySnapshot, e) -> { + if (e != null) { + mProgress.setVisibility(View.GONE); + e.printStackTrace(); + return; + } + assert querySnapshot != null; + if (!querySnapshot.isEmpty()) { + for (DocumentChange doc : querySnapshot.getDocumentChanges()) { + if (doc.getDocument().exists()) { + if (doc.getType() == DocumentChange.Type.ADDED) { + mProgress.setVisibility(View.GONE); + Comment comment = doc.getDocument().toObject(Comment.class); + commentList.add(comment); + mAdapter.notifyDataSetChanged(); + } + } + } + if (commentList.isEmpty()) { + mProgress.setVisibility(View.GONE); + } + } else { + mProgress.setVisibility(View.GONE); + } + + + }); + } + + private static class SendNotificationAsyncTask extends AsyncTask { + final APIService apiService; + final Notification notification; + + private SendNotificationAsyncTask(Notification notification) { + this.notification = notification; + apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class); + } + + @Override + protected Void doInBackground(Void... jk) { + FirebaseDatabase.getInstance().getReference().child("Tokens").child(notification.getNotifyTo()).child("token").addListenerForSingleValueEvent(new ValueEventListener() { + @Override + public void onDataChange(@NonNull DataSnapshot dataSnapshot) { + String usertoken = dataSnapshot.getValue(String.class); + NotificationSender sender = new NotificationSender(notification, usertoken); + apiService.sendNotifcation(sender).enqueue(new Callback() { + @Override + public void onResponse(@NonNull Call call, @NonNull Response response) { + } + + @Override + public void onFailure(@NonNull Call call, @NonNull Throwable t) { + + } + }); + } + + @Override + public void onCancelled(@NonNull DatabaseError databaseError) { + + } + }); + return null; + } + } + +} \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/PostIssue.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/PostIssue.java new file mode 100644 index 0000000..2ded5f4 --- /dev/null +++ b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/PostIssue.java @@ -0,0 +1,786 @@ +package com.quantum_guys.dncc_eco_sync.ui.activities.issue; + +import static android.view.View.GONE; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.graphics.Color; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Parcelable; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.EditText; +import android.widget.RelativeLayout; +import android.widget.Spinner; +import android.widget.Switch; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.widget.Toolbar; +import androidx.constraintlayout.widget.ConstraintLayout; +import androidx.core.content.ContextCompat; +import androidx.viewpager.widget.ViewPager; + +import com.afollestad.materialdialogs.MaterialDialog; +import com.google.firebase.auth.FirebaseAuth; +import com.google.firebase.auth.FirebaseUser; +import com.marcoscg.dialogsheet.DialogSheet; +import com.quantum_guys.dncc_eco_sync.R; +import com.quantum_guys.dncc_eco_sync.adapters.PagerPhotosAdapter; +import com.quantum_guys.dncc_eco_sync.models.Images; +import com.quantum_guys.dncc_eco_sync.service.UploadService; +import com.quantum_guys.dncc_eco_sync.utils.MathView; +import com.quantum_guys.dncc_eco_sync.utils.RichEditor; +import com.tbuonomo.viewpagerdotsindicator.DotsIndicator; +import com.yalantis.ucrop.UCrop; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Random; + +import es.dmoral.toasty.Toasty; + +@SuppressWarnings("UnusedAssignment") +public class PostIssue extends AppCompatActivity { + + List imagesList; + ViewPager pager; + Spinner type; + PagerPhotosAdapter adapter; + final ArrayList uploadedImagesUrl = new ArrayList<>(); + String tag; + RichEditor mRichEd; + private FirebaseUser mCurrentUser; + private DotsIndicator indicator; + private RelativeLayout indicator_holder; + private int selectedIndex; + private SharedPreferences sharedPreferences; + private int serviceCount; + private ConstraintLayout codeLayout; + EditText latexText, codeText; + public static void startActivity(Context context) { + Intent intent = new Intent(context, PostIssue.class); + context.startActivity(intent); + } + boolean isHead; + @NonNull + public static String random() { + Random generator = new Random(); + StringBuilder randomStringBuilder = new StringBuilder(); + int randomLength = generator.nextInt(10); + char tempChar; + for (int i = 0; i < randomLength; i++) { + tempChar = (char) (generator.nextInt(96) + 32); + randomStringBuilder.append(tempChar); + } + return randomStringBuilder.toString(); + } + + public static void insertData(String latexData, RichEditor mEditor) { + mEditor.insertLatex(latexData); + } + + public static void addExtraLatex(String data, EditText latexText) { + int start = Math.max(latexText.getSelectionStart(), 0); + int end = Math.max(latexText.getSelectionEnd(), 0); + latexText.getText().replace(Math.min(start, end), Math.max(start, end), + data, 0, data.length()); + } + + @Override + public boolean onSupportNavigateUp() { + + onBackPressed(); + + return true; + } + + @Override + public void onBackPressed() { + new MaterialDialog.Builder(this) + .title("Discard") + .content("Are you sure do you want to go back?") + .positiveText("Yes") + .canceledOnTouchOutside(false) + .cancelable(false) + .onPositive((dialog, which) -> finish()) + .negativeText("No") + .show(); + } + + Switch postAnnounimasentSwitch; + + Boolean isAnonymous; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setTheme(R.style.AppTheme); + setContentView(R.layout.activity_issue_image); + imagesList = getIntent().getParcelableArrayListExtra("imagesList"); + if (imagesList.isEmpty()) { + finish(); + } + Window window = this.getWindow(); + window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); + window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); + window.setStatusBarColor(ContextCompat.getColor(getApplicationContext(), R.color.statusBar)); + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + toolbar.setTitle("Issue with Image"); + latexText = findViewById(R.id.latex_equation); + codeText = findViewById(R.id.code); + type = findViewById(R.id.spinner_type); + postAnnounimasentSwitch = findViewById(R.id.switch1); + ArrayAdapter arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.item_type_x)); + arrayAdapter.setDropDownViewResource(android.R.layout.simple_expandable_list_item_1); + type.setAdapter(arrayAdapter); + type.setOnItemSelectedListener(new TypeXSpinnerClass()); + + try { + Objects.requireNonNull(getSupportActionBar()).setTitle("Issue with Image"); + } catch (Exception e) { + e.printStackTrace(); + } + Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setDisplayShowHomeEnabled(true); + + pager = findViewById(R.id.pager); + indicator = findViewById(R.id.indicator); + indicator_holder = findViewById(R.id.indicator_holder); + + postAnnounimasentSwitch.setOnCheckedChangeListener((compoundButton, b) -> { + isAnonymous = b; + }); + + indicator.setDotsClickable(true); + adapter = new PagerPhotosAdapter(this, imagesList); + pager.setAdapter(adapter); + mRichEd = findViewById(R.id.editPost); + setUpLaTexEditor(mRichEd,null, 200); + if (imagesList.size() > 1) { + indicator_holder.setVisibility(View.VISIBLE); + indicator.setViewPager(pager); + } else { + indicator_holder.setVisibility(GONE); + } + + FirebaseAuth mAuth = FirebaseAuth.getInstance(); + mCurrentUser = mAuth.getCurrentUser(); + + sharedPreferences = getSharedPreferences("uploadservice", MODE_PRIVATE); + serviceCount = sharedPreferences.getInt("count", 0); + + } + + public void setUpLaTexEditor(RichEditor mEditor, MathView mathView, int height) { + mEditor.setEditorHeight(height); + mEditor.setEditorFontSize(18); + mEditor.setPadding(10, 10, 10, 10); + mEditor.setPlaceholder("Start Witting your issue/complain here..."); + mEditor.setOnTextChangeListener(text -> { + try { + mathView.setDisplayText(text); + } catch (NullPointerException ignored) { + + } + }); + codeLayout = findViewById(R.id.code_editor); + + findViewById(R.id.action_undo).setOnClickListener(v -> mEditor.undo()); + + findViewById(R.id.action_redo).setOnClickListener(v -> mEditor.redo()); + + findViewById(R.id.action_bold).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_bold).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_bold).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setBold(); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_italic).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_italic).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_italic).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setItalic(); + isChanged = !isChanged; + } + }); + + + findViewById(R.id.action_subscript).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_subscript).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_subscript).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setSubscript(); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_superscript).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_superscript).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_superscript).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setSuperscript(); + isChanged = !isChanged; + } + }); + + + findViewById(R.id.action_strikethrough).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_strikethrough).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_strikethrough).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setStrikeThrough(); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_underline).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_underline).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_underline).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setUnderline(); + isChanged = !isChanged; + } + }); + + + + + + findViewById(R.id.action_heading1).setOnClickListener(v ->{ + if(!isHead){ + findViewById(R.id.action_heading1).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_heading1).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + isHead=!isHead; + mEditor.setHeading(1); + }); + + findViewById(R.id.action_heading2).setOnClickListener(v -> { + if(!isHead){ + findViewById(R.id.action_heading2).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_heading2).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + isHead=!isHead; + mEditor.setHeading(2); + }); + + findViewById(R.id.action_heading3).setOnClickListener(v -> { + if(!isHead){ + findViewById(R.id.action_heading3).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_heading3).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + isHead=!isHead; + mEditor.setHeading(3); + + }); + + findViewById(R.id.action_heading4).setOnClickListener(v -> { + if(!isHead){ + findViewById(R.id.action_heading4).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_heading4).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + isHead=!isHead; + mEditor.setHeading(4); + }); + + findViewById(R.id.action_heading5).setOnClickListener(v -> { + if(!isHead){ + findViewById(R.id.action_heading5).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_heading5).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + isHead=!isHead; + mEditor.setHeading(5); + }); + + findViewById(R.id.action_heading6).setOnClickListener(v -> { + if(!isHead){ + findViewById(R.id.action_heading6).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_heading6).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + isHead=!isHead; + mEditor.setHeading(6); + }); + + + findViewById(R.id.action_txt_color).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @SuppressLint("ResourceType") + @Override + public void onClick(View v) { + if(!isChanged){ + findViewById(R.id.action_txt_color).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_txt_color).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setTextColor(isChanged ? Color.BLACK : getResources().getColor(R.color.colorAccentt)); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_bg_color).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @SuppressLint("ResourceType") + @Override + public void onClick(View v) { + if(!isChanged){ + findViewById(R.id.action_bg_color).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_bg_color).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setTextBackgroundColor(isChanged ? Color.TRANSPARENT : getResources().getColor(R.color.backG)); + isChanged = !isChanged; + } + }); + + + findViewById(R.id.action_indent).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_indent).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_indent).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setIndent(); + isChanged = !isChanged; + } + }); + + + findViewById(R.id.action_outdent).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_outdent).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_outdent).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setOutdent(); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_align_left).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_align_left).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_align_left).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setAlignLeft(); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_align_center).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_align_center).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_align_center).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setAlignCenter(); + isChanged = !isChanged; + } + }); + + findViewById(R.id.insert_code).setOnClickListener(view -> { + if (codeLayout.getVisibility() == View.GONE) { + findViewById(R.id.insert_code).setBackgroundColor(getResources().getColor(R.color.selectted)); + codeLayout.setVisibility(View.VISIBLE); + findViewById(R.id.submit_code).setOnClickListener(view115 -> { + String data1 = codeText.getText().toString(); + mRichEd.setCode(data1); + data1 = ""; + codeText.setText(""); + codeLayout.setVisibility(View.GONE); + }); + } else { + findViewById(R.id.insert_code).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + codeLayout.setVisibility(View.GONE); + } + }); + + findViewById(R.id.action_align_right).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_align_right).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_align_right).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setAlignRight(); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_blockquote).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_blockquote).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_blockquote).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setBlockquote(); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_insert_bullets).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_insert_bullets).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_insert_bullets).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setBullets(); + isChanged = !isChanged; + } + }); + + findViewById(R.id.action_insert_numbers).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_insert_numbers).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_insert_numbers).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.setNumbers(); + isChanged = !isChanged; + } + }); + + + View latexView = findViewById(R.id.latext_editor); + + + findViewById(R.id.insert_latex).setOnClickListener(view -> { + if (latexView.getVisibility() == View.GONE) { + latexView.setVisibility(View.VISIBLE); + findViewById(R.id.insert_latex).setBackgroundColor(getResources().getColor(R.color.selectted)); + MathView mathView1 = findViewById(R.id.mathView); + latexText.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { + } + + @Override + public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { + mathView1.setDisplayText("\\(" + charSequence.toString() + "\\)"); + } + + @Override + public void afterTextChanged(Editable editable) { + + } + }); + findViewById(R.id.submit_latex).setOnClickListener(view115 -> { + String data1 = latexText.getText().toString(); + data1 = data1.replace(" ", ""); + //Toast.makeText(PostText.this, data, Toast.LENGTH_SHORT).show(); + insertData(data1, mEditor); + latexText.setText(""); + data1 = ""; + latexView.setVisibility(View.GONE); + }); + findViewById(R.id.action_frac).setOnClickListener(view116 -> addExtraLatex("\\frac{}{}", latexText)); + findViewById(R.id.action_power).setOnClickListener(view117 -> addExtraLatex("^", latexText)); + findViewById(R.id.action_sub).setOnClickListener(view118 -> addExtraLatex("_", latexText)); + findViewById(R.id.action_root).setOnClickListener(view119 -> addExtraLatex("\\sqrt{a}", latexText)); + findViewById(R.id.action_alpha).setOnClickListener(view114 -> addExtraLatex("\\alpha", latexText)); + findViewById(R.id.action_diff).setOnClickListener(view113 -> addExtraLatex("\\frac{d}{dx}()", latexText)); + findViewById(R.id.action_int).setOnClickListener(view112 -> addExtraLatex("\\int_{}^{}", latexText)); + findViewById(R.id.action_therefore).setOnClickListener(view111 -> addExtraLatex("\\therefore", latexText)); + findViewById(R.id.action_theta).setOnClickListener(view110 -> addExtraLatex("\\theta", latexText)); + findViewById(R.id.action_mu).setOnClickListener(view19 -> addExtraLatex("\\mu", latexText)); + findViewById(R.id.action_pi).setOnClickListener(view18 -> addExtraLatex("\\pi", latexText)); + findViewById(R.id.action_lanbda).setOnClickListener(view17 -> addExtraLatex("\\lambda", latexText)); + findViewById(R.id.action_ohm).setOnClickListener(view16 -> addExtraLatex("\\ohm", latexText)); + findViewById(R.id.action_omega).setOnClickListener(view15 -> addExtraLatex("\\omega", latexText)); + findViewById(R.id.action_hat).setOnClickListener(view13 -> addExtraLatex("\\hat{A}", latexText)); + findViewById(R.id.action_over).setOnClickListener(view14 -> addExtraLatex("\\vec{A}", latexText)); + findViewById(R.id.action_enter).setOnClickListener(view12 -> addExtraLatex("\\\\", latexText)); + findViewById(R.id.action_space).setOnClickListener(view1 -> addExtraLatex("\\;", latexText)); + } else { + findViewById(R.id.insert_latex).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + latexView.setVisibility(View.GONE); + } + }); + + findViewById(R.id.action_insert_checkbox).setOnClickListener(new View.OnClickListener() { + private boolean isChanged; + @Override + public void onClick(View view) { + if(!isChanged){ + findViewById(R.id.action_insert_checkbox).setBackgroundColor(getResources().getColor(R.color.selectted)); + }else{ + findViewById(R.id.action_insert_checkbox).setBackgroundColor(getResources().getColor(R.color.colorAccentt)); + } + mEditor.insertTodo(); + isChanged = !isChanged; + } + }); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + MenuInflater menuInflater = getMenuInflater(); + menuInflater.inflate(R.menu.menu_image_post, menu); + return true; + } + + @SuppressLint("NonConstantResourceId") + @Override + public boolean onOptionsItemSelected(MenuItem item) { + + if (item.getItemId() == R.id.action_post) { + if (tag != null) { + new DialogSheet(this) + .setRoundedCorners(true) + .setColoredNavigationBar(true) + .setPositiveButton("Yes", v -> { + sharedPreferences.edit().putInt("count", ++serviceCount).apply(); + Intent intent = new Intent(PostIssue.this, UploadService.class); + intent.putExtra("count", serviceCount); + intent.putStringArrayListExtra("uploadedImagesUrl", uploadedImagesUrl); + intent.putParcelableArrayListExtra("imagesList", (ArrayList) imagesList); + intent.putExtra("notification_id", (int) System.currentTimeMillis()); + intent.putExtra("current_id", mCurrentUser.getUid()); + try { + intent.putExtra("description", mRichEd.getHtml()); + } catch (NullPointerException h) { + intent.putExtra("description", " "); + } + intent.putExtra("tag", tag); + intent.setAction(UploadService.ACTION_START_FOREGROUND_SERVICE); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + startForegroundService(intent); + } else { + startService(intent); + } + Toasty.info(PostIssue.this, "Uploading images..", Toasty.LENGTH_SHORT, true).show(); + finish(); + }) + .setNegativeButton("No", v -> { + }) + .setTitle("Upload") + .setMessage("Are you sure is this the content you want to upload?") + .show(); + } else { + Toasty.error(this, "Select a tag", Toast.LENGTH_SHORT).show(); + } + return true; + } + return super.onOptionsItemSelected(item); + } + + + public void deleteItem() { + + new MaterialDialog.Builder(this) + .title("Remove") + .content("Are you sure do you want to remove this image?") + .positiveText("Yes") + .onPositive((dialog, which) -> { + + if (imagesList.size() == 1) { + finish(); + return; + } + + imagesList.remove(pager.getCurrentItem()); + + adapter = new PagerPhotosAdapter(PostIssue.this, imagesList); + pager.setAdapter(adapter); + indicator.setViewPager(pager); + + if (imagesList.size() > 1) { + indicator_holder.setVisibility(View.VISIBLE); + indicator.setViewPager(pager); + } else { + indicator_holder.setVisibility(GONE); + } + + }) + .negativeText("No") + .show(); + } + + public void openCropItem() { + + selectedIndex = pager.getCurrentItem(); + UCrop.Options options = new UCrop.Options(); + options.setCompressionFormat(Bitmap.CompressFormat.PNG); + options.setCompressionQuality(90); + options.setShowCropGrid(true); + + + UCrop.of(Uri.fromFile(new File(imagesList.get(selectedIndex).getOg_path())), Uri.fromFile(new File(getCacheDir(), imagesList.get(selectedIndex).getName() + "_" + random() + "_edit.png"))) + .withAspectRatio(1, 1) + .withOptions(options) + .start(this); + + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { + super.onActivityResult(requestCode, resultCode, data); + + if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) { + + long old_id = imagesList.get(selectedIndex).getId(); + String old_name = imagesList.get(selectedIndex).getName(); + String old_path = imagesList.get(selectedIndex).getOg_path(); + + imagesList.remove(selectedIndex); + imagesList.add(selectedIndex, new Images(old_name, old_path, Objects.requireNonNull(UCrop.getOutput(Objects.requireNonNull(data))).getPath(), old_id)); + adapter = new PagerPhotosAdapter(this, imagesList); + pager.setAdapter(adapter); + indicator.setViewPager(pager); + adapter.notifyDataSetChanged(); + pager.setCurrentItem(selectedIndex, true); + + } else if (resultCode == UCrop.RESULT_ERROR) { + Throwable throwable = UCrop.getError(Objects.requireNonNull(data)); + Objects.requireNonNull(throwable).printStackTrace(); + Toasty.error(this, "Error cropping : " + throwable.getMessage(), Toasty.LENGTH_SHORT, true).show(); + } + + + } + + + public void deleteItem(View view) { + + new MaterialDialog.Builder(this) + .title("Remove") + .content("Are you sure want to remove this image?") + .positiveText("Yes") + .onPositive((dialog, which) -> { + + if (imagesList.size() == 1) { + finish(); + return; + } + + imagesList.remove(pager.getCurrentItem()); + + adapter = new PagerPhotosAdapter(PostIssue.this, imagesList); + pager.setAdapter(adapter); + indicator.setViewPager(pager); + + if (imagesList.size() > 1) { + indicator_holder.setVisibility(View.VISIBLE); + indicator.setViewPager(pager); + } else { + indicator_holder.setVisibility(GONE); + } + + }) + .negativeText("No") + .show(); + } + + public void openCropItem(View view) { + + selectedIndex = pager.getCurrentItem(); + UCrop.Options options = new UCrop.Options(); + options.setCompressionFormat(Bitmap.CompressFormat.PNG); + options.setCompressionQuality(90); + options.setShowCropGrid(true); + + UCrop.of(Uri.fromFile(new File(imagesList.get(selectedIndex).getOg_path())), Uri.fromFile(new File(getCacheDir(), imagesList.get(selectedIndex).getName() + "_" + random() + "_edit.png"))) + .withAspectRatio(4, 3) + .withOptions(options) + .start(this); + } + + + class TypeXSpinnerClass implements AdapterView.OnItemSelectedListener { + public void onItemSelected(AdapterView parent, View v, int position, long id) { + tag = parent.getItemAtPosition(position).toString(); + } + + @Override + public void onNothingSelected(AdapterView adapterView) { + + } + } + private void addExtraCode(EditText codeText) { + int start = Math.max(codeText.getSelectionStart(), 0); + int end = Math.max(codeText.getSelectionEnd(), 0); + codeText.getText().replace(Math.min(start, end), Math.max(start, end), + " ", 0, " ".length()); + } +} \ No newline at end of file diff --git a/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/SingleIssueView.java b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/SingleIssueView.java new file mode 100644 index 0000000..ff5efef --- /dev/null +++ b/android-app/app/src/main/java/com/quantum_guys/dncc_eco_sync/ui/activities/issue/SingleIssueView.java @@ -0,0 +1,185 @@ +package com.quantum_guys.dncc_eco_sync.ui.activities.issue; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Color; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ProgressBar; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.appcompat.app.AppCompatDelegate; +import androidx.appcompat.widget.Toolbar; +import androidx.paging.PagedList; +import androidx.recyclerview.widget.DefaultItemAnimator; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.firebase.ui.firestore.paging.FirestorePagingAdapter; +import com.firebase.ui.firestore.paging.FirestorePagingOptions; +import com.firebase.ui.firestore.paging.LoadingState; +import com.google.android.material.bottomsheet.BottomSheetDialog; +import com.google.firebase.firestore.FirebaseFirestore; +import com.google.firebase.firestore.Query; +import com.quantum_guys.dncc_eco_sync.R; +import com.quantum_guys.dncc_eco_sync.adapters.PostViewHolder; +import com.quantum_guys.dncc_eco_sync.models.Issue; +import com.quantum_guys.dncc_eco_sync.models.Post; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class SingleIssueView extends AppCompatActivity { + RecyclerView mRecyclerView; + private View statsheetView; + private BottomSheetDialog mmBottomSheetDialog; + private ProgressBar pbar; + private FirebaseFirestore mFirestore; + + + @Override + public boolean onSupportNavigateUp() { + onBackPressed(); + return super.onSupportNavigateUp(); + } + + + @SuppressLint("InflateParams") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + SharedPreferences sharedPreferences = getSharedPreferences("Theme", Context.MODE_PRIVATE); + String themeName = sharedPreferences.getString("ThemeName", "Default"); + if (themeName.equalsIgnoreCase("TealTheme")) { + setTheme(R.style.TealTheme); + } else if (themeName.equalsIgnoreCase("VioleteTheme")) { + setTheme(R.style.VioleteTheme); + } else if (themeName.equalsIgnoreCase("PinkTheme")) { + setTheme(R.style.PinkTheme); + } else if (themeName.equalsIgnoreCase("DelRio")) { + setTheme(R.style.DelRio); + } else if (themeName.equalsIgnoreCase("DarkTheme")) { + AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); + setTheme(R.style.Dark); + } else if (themeName.equalsIgnoreCase("Lynch")) { + setTheme(R.style.Lynch); + } else { + setTheme(R.style.AppTheme); + } + + setContentView(R.layout.activity_single_post_view); + + String post_id = getIntent().getStringExtra("post_id"); + + Toolbar toolbar = findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + toolbar.setTitleTextColor(Color.WHITE); + toolbar.setTitle("Issue"); + + Objects.requireNonNull(getSupportActionBar()).setTitle("Issue"); + getSupportActionBar().setDisplayShowHomeEnabled(true); + + if (post_id == null) { + finish(); + } + + if (!TextUtils.isEmpty(post_id)) { + + pbar = findViewById(R.id.pbar); + mFirestore = FirebaseFirestore.getInstance(); + + statsheetView = getLayoutInflater().inflate(R.layout.stat_bottom_sheet_dialog, null); + mmBottomSheetDialog = new BottomSheetDialog(this); + mmBottomSheetDialog.setContentView(statsheetView); + mmBottomSheetDialog.setCanceledOnTouchOutside(true); + + List mPostsList = new ArrayList<>(); + + mRecyclerView = findViewById(R.id.recyclerView); + mRecyclerView.setItemAnimator(new DefaultItemAnimator()); + mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); + mRecyclerView.setHasFixedSize(true); + pbar.setVisibility(View.VISIBLE); + getPosts(post_id); + + + } else { + finish(); + } + + } + + private void getPosts(final String post_id) { + PagedList.Config config = new PagedList.Config.Builder() + .setEnablePlaceholders(false) + .setPrefetchDistance(1) + .setPageSize(1) + .build(); + Query mQuery = mFirestore.collection("Issues") + .whereEqualTo("postId", post_id); + + FirestorePagingOptions options = new FirestorePagingOptions.Builder() + .setLifecycleOwner(this) + .setQuery(mQuery, config, Issue.class) + .build(); + // Instantiate Paging Adapter + + // getApplicationContext().getSharedPreferences("Posts", MODE_PRIVATE).edit().putInt("num", getItemCount()).apply(); + FirestorePagingAdapter mAdapter = new FirestorePagingAdapter(options) { + @NonNull + @Override + public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View view = getLayoutInflater().inflate(R.layout.item_feed_post, parent, false); + return new PostViewHolder(view); + } + + @Override + protected void onBindViewHolder(@NonNull PostViewHolder holder, int position, @NonNull Issue issue) { + holder.bind(issue, holder, position, mmBottomSheetDialog, statsheetView, false); + } + + @Override + protected void onError(@NonNull Exception e) { + super.onError(e); + Log.e("MainActivity", e.getMessage()); + } + + @Override + protected void onLoadingStateChanged(@NonNull LoadingState state) { + switch (state) { + case LOADING_INITIAL: + case LOADING_MORE: + pbar.setVisibility(View.VISIBLE); + break; + + case LOADED: + + case FINISHED: + if (getItemCount() == 0) finish(); + pbar.setVisibility(View.GONE); + // getApplicationContext().getSharedPreferences("Posts", MODE_PRIVATE).edit().putInt("num", getItemCount()).apply(); + break; + + case ERROR: + Toast.makeText( + getApplicationContext(), + "Error Occurred!", + Toast.LENGTH_SHORT + ).show(); + + pbar.setVisibility(View.GONE); + break; + } + } + + }; + mRecyclerView.setAdapter(mAdapter); + } +} diff --git a/android-app/app/src/main/res/layout/activity_issue_image.xml b/android-app/app/src/main/res/layout/activity_issue_image.xml new file mode 100644 index 0000000..7dfee6c --- /dev/null +++ b/android-app/app/src/main/res/layout/activity_issue_image.xml @@ -0,0 +1,216 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dncc.geojson b/dncc.geojson index 5d1872f..62eceaa 100644 --- a/dncc.geojson +++ b/dncc.geojson @@ -2,7 +2,6 @@ "type" : "FeatureCollection", "features" : [ - { "type" : "Feature", "id" : 583, diff --git a/react-app/components/ContractorEntry/AddContractorEntry.js b/react-app/components/ContractorEntry/AddContractorEntry.js index 2f85fa1..109ec7e 100644 --- a/react-app/components/ContractorEntry/AddContractorEntry.js +++ b/react-app/components/ContractorEntry/AddContractorEntry.js @@ -29,42 +29,42 @@ const AddContractorEntry = ({ props, contractorId }) => { .then((response) => { console.log(response) toast.success('Worker Entry added successfully') - // toast.custom((t) => ( - //
- //
- //
- //
- // - //
- //
- //

- // {response.data.landfill.name} - //

- //

- // Distance {response.data.bill.distance} KM .It will take{' '} - // {Number(response.data.bill.duration).toFixed(2)} min. - //

- //
- //
- //
- //
- // - //
- //
- // )) + // toast.custom((t) => ( + //
+ //
+ //
+ //
+ // + //
+ //
+ //

+ // {response.data.landfill.name} + //

+ //

+ // Distance {response.data.bill.distance} KM .It will take{' '} + // {Number(response.data.bill.duration).toFixed(2)} min. + //

+ //
+ //
+ //
+ //
+ // + //
+ //
+ // )) handleClose() }) .catch((error) => console.log(error)) diff --git a/react-app/components/layout/Sidebar.js b/react-app/components/layout/Sidebar.js index 0522dcf..9c422e3 100644 --- a/react-app/components/layout/Sidebar.js +++ b/react-app/components/layout/Sidebar.js @@ -114,7 +114,7 @@ const Sidebar = () => { const token = localStorage.getItem('token') console.log({ token }) const res = axios - .get(getBaseUrl() + '/mycontractors', { + .get(getBaseUrl() + '/myContractors', { headers: { Authorization: `Bearer ${token}`, }, @@ -126,7 +126,7 @@ const Sidebar = () => { setManagedContractors(response.data) setLoading(false) console.log(response) - router.push('/employee-entry/' + response.data[0].id) + router.push('/contractor/' + response.data[0].id) }) .catch((error) => { setLoading(false) @@ -264,6 +264,34 @@ const Sidebar = () => { )} )} + +{type === 'ContractorManager' && ( + <> + {loading ? ( +

+ Loading Contractors... +

+ ) : managedContractors.length > 0 ? ( + managedContractors.map((contractor, index) => ( + + )) + ) : ( +

+ No ContractorManager found +

+ )} + + )} + diff --git a/react-app/pages/contractor/[contractirId].js b/react-app/pages/contractor/[contractirId].js new file mode 100644 index 0000000..e7afee4 --- /dev/null +++ b/react-app/pages/contractor/[contractirId].js @@ -0,0 +1,183 @@ +/* eslint-disable multiline-ternary */ +/* eslint-disable react/react-in-jsx-scope */ +import { useEffect, useState } from 'react' +import axios from 'axios' +import { useRouter } from 'next/router' +import { getBaseUrl } from '../../utils/url' +import StsItemsSkeleton from '../../components/Stss/StsItemsSkeleton' +import StsEntryItems from '../../components/StsEntrys/StsEntryItems' +import Layout from '../../components/layout' +import MapView from '../../components/common/MapView' +import AddWasteEntry from '../../components/WasteEntry/AddWasteEntry' +import WasteItemsSkeleton from '../../components/WasteEntrys/WasteEntryItemsSkeleton' +import WasteEntryItems from '../../components/WasteEntrys/WasteEntryItems' +import { NoSSR } from '../../components/common/NoSSR' +import ProgressBar from '../../components/common/ProgressBar' +import AddStsEntry from '../../components/StsEntry/AddStsEntry' + +export default function VehicleEntry () { + const [loading, setLoading] = useState(true) + const [loadingInfo, setLoadingInfo] = useState(true) + const [vehicleEntries, setVehicleEntries] = useState([]) + const [wasteEntries, setWasteEntries] = useState([]) + + const [sts, setSts] = useState({}) + + const [contractorId, setStsId] = useState(null) + + const router = useRouter() + + useEffect(() => { + setStsId(router.query.contractorId) + }, [router.query.contractorId]) + + useEffect(() => { + if (contractorId === null) return + setLoadingInfo(true) + const token = localStorage.getItem('token') + if (token) { + axios + .get(getBaseUrl() + `/contractor/${contractorId}`, { + headers: { + Authorization: `Bearer ${token}` + } + }) + .then((res) => { + setLoadingInfo(false) + setSts(res.data) + console.log(res.data) + }) + .catch((err) => { + setLoadingInfo(false) + console.log(err) + }) + } + }, [contractorId]) + + useEffect(() => { + if (contractorId === null) return + setLoading(true) + const token = localStorage.getItem('token') + if (token.length > 0) { + axios + .get(getBaseUrl() + `/sts/${contractorId}/entry`, { + headers: { + Authorization: `Bearer ${token}` + } + }) + .then((res) => { + console.log(res.data) + res.data.sort((a, b) => b.id - a.id) + setVehicleEntries(res.data) + setLoading(false) + }) + .catch((err) => { + setLoading(false) + console.log(err) + }) + } + }, [contractorId]) + + useEffect(() => { + if (contractorId === null) return + setLoading(true) + const token = localStorage.getItem('token') + if (token.length > 0) { + axios + .get(getBaseUrl() + `/sts/${contractorId}/add`, { + headers: { + Authorization: `Bearer ${token}` + } + }) + .then((res) => { + console.log(res.data) + res.data.sort((a, b) => b.id - a.id) + setWasteEntries(res.data) + setLoading(false) + }) + .catch((err) => { + setLoading(false) + console.log(err) + }) + } + }, [contractorId]) + + return ( + +
+
+
+

STS Info

+
+ {loadingInfo ? ( +
+
+
+
+ ) : ( +
+
+
+

Ward: {sts.wardNumber}

+

Address: {sts.address}

+ +
+
+ +
+
+
+ )} +
+ +
+
+
+

+ Vehicle Entries{' '} +

+
+ {contractorId && } +
+
+ {loading ? ( + + ) : ( + + )} +
+ +
+
+

+ Waste Entries +

+
+ {contractorId && } +
+
+ {loading ? ( + + ) : ( + + )} +
+
+
+
+ ) +} + +VehicleEntry.getLayout = function getLayout (page) { + return {page} +}