From 6c7615110dcf8334196bbfddfd89b684e4ceee4f Mon Sep 17 00:00:00 2001
From: aidahosa1 <aisosa_idahosa@brown.edu>
Date: Fri, 17 May 2024 21:30:02 -0400
Subject: GOD IS GOOD

---
 .../views/collections/CollectionCardDeckView.tsx   | 231 +++++++++++++--------
 1 file changed, 140 insertions(+), 91 deletions(-)

(limited to 'src/client/views/collections/CollectionCardDeckView.tsx')

diff --git a/src/client/views/collections/CollectionCardDeckView.tsx b/src/client/views/collections/CollectionCardDeckView.tsx
index e96fbc161..42c82ca74 100644
--- a/src/client/views/collections/CollectionCardDeckView.tsx
+++ b/src/client/views/collections/CollectionCardDeckView.tsx
@@ -24,6 +24,7 @@ import { ImageField, PdfField, URLField } from '../../../fields/URLField';
 import { GPTPopup } from '../pdf/GPTPopup/GPTPopup';
 import { GPTPopupMode } from '../pdf/GPTPopup/GPTPopup';
 import { reaction } from 'mobx';
+import { NumListCast } from '../../../fields/Doc';
 @observer
 export class CollectionCardView extends CollectionSubView() {
 
@@ -32,8 +33,42 @@ export class CollectionCardView extends CollectionSubView() {
     // documents themselves
 
     @observable hoveredNodeIndex = -1;
+    //index to group
+    @observable customGroupDictionary: Map<number, number>[] = [new Map<number, number>(), new Map<number, number>(), new Map<number, number>()];
+
 
     @computed get myChildLayoutPairs() {
+        let activeGroups = NumListCast(this._props.Document.visibleGroupNumbers);
+        let currCustom = NumCast(this._props.Document.customSortNumber);
+
+        // console.log("Active Groups:", activeGroups);
+
+        for (let i=0; i< activeGroups.length; i++){
+            console.log("Active Groups" + activeGroups[i])
+        }
+        // console.log("Current Custom Sort Number:", currCustom);
+
+        if (activeGroups.length <= 0) {
+            return this.childLayoutPairs.filter(l => l.layout.type != DocumentType.LINK);
+        }
+
+        if (StrCast(this._props.Document.cardSort).includes("custom")) {
+            return this.childLayoutPairs.filter((l, index) => {
+                if (l.layout.type === DocumentType.LINK) {
+                    return false;
+                }
+
+                // Get the group number for the current index from the customGroupDictionary
+                const groupNumber = this.customGroupDictionary[currCustom].get(index);
+
+                // console.log(`Index: ${index}, Group Number: ${groupNumber}`);
+
+                // Check if the group number is in the active groups
+                return groupNumber !== undefined && activeGroups.includes(groupNumber);
+            });
+        }
+
+        // Default return for non-custom cardSort or other cases, filtering out links
         return this.childLayoutPairs.filter(l => l.layout.type != DocumentType.LINK);
     }
 
@@ -90,6 +125,9 @@ export class CollectionCardView extends CollectionSubView() {
         if (this._props.Document.customHashMap != undefined){
             this.customGroupDictionary = this.getCustoms(StrListCast(this._props.Document.customHashMap))
         }
+        // this._props.Document.visibleGroupNumbers = new List<number>([1,2,3,4])
+
+
 
         reaction(
             () => this._props.Document.cardSort,
@@ -101,7 +139,6 @@ export class CollectionCardView extends CollectionSubView() {
         );
     }
 
-    @observable customGroupDictionary: Map<number, number>[] = [new Map<number, number>(), new Map<number, number>(), new Map<number, number>()];
 
     @computed get mapToField(): List<string> {
         const resultList = new List<string>(); 
@@ -272,7 +309,8 @@ export class CollectionCardView extends CollectionSubView() {
             case 'custom':
                 return this.sort(sorted, 'custom', desc);
             case 'chat':
-                return { docs: this.sortedDocs || this.myChildLayoutPairs}; // Use the sorted docs from the observable
+                return this.sort(this.myChildLayoutPairs, 'gpt', BoolCast(this.layoutDoc.sortDesc));            
+                
             default:
                 docs = this.myChildLayoutPairs;
                 return { docs };
@@ -458,7 +496,8 @@ export class CollectionCardView extends CollectionSubView() {
             // const childPair = { layout: doc, data: doc };
 
             const isHovered = this.hoveredNodeIndex === index;
-            const childPairIndex = this.myChildLayoutPairs.indexOf(childPair);
+            // const childPairIndex = this.myChildLayoutPairs.indexOf(childPair);
+            const childPairIndex  = this.childLayoutPairs.filter(d => d.layout.type != DocumentType.LINK).indexOf(childPair)
             const realIndex = this.sortedDocsType.docs.filter(d => !SelectionManager.IsSelected(d.layout)).indexOf(childPair);
             const calcRowIndex = this.overflowIndexCalc(realIndex);
 
@@ -501,6 +540,8 @@ export class CollectionCardView extends CollectionSubView() {
                     {this.displayDoc(childPair, childScreenToLocal)}
 
                     {this._props.Document.cardSort == 'custom' ? this.renderButtons(childPairIndex) : ''}
+                    {this._props.Document.cardSort == 'chat' ? this.renderButtons(childPairIndex, childPair.layout, true) : ''}
+
                 </div>
             );
         });
@@ -512,38 +553,23 @@ export class CollectionCardView extends CollectionSubView() {
     
     
 
-    @action toggleButton(childPairIndex: number, buttonID: number) {
-        this.customGroupDictionary[NumCast(this._props.Document.customSortNumber)].set(childPairIndex, buttonID);
-        this._props.Document.customHashMap = this.mapToField
-
-        // Cast(selected.Document.data, WebField, null)?.url?.href)
-
-        //note richtext
-
-        // StrCast(selected.Document.data, Cast(selected.Document.data, WebField, null)?.url?.href)
-
-
-
-        // const
-        const imgurlperchance = Cast(this.childDocs[1].data, ImageField, null)?.url.href;
-        const perchance = this.imageUrlToBase64(imgurlperchance)
-        // const imgurlperchance = Cast(this.childDocs[1].data, PdfField, null)?.url.;
-
-
-        // console.log('Print Front of cards: ' + RTFCast(DocCast(this.dataDoc[this.fieldKey + '_0']).text)?.Text);
-        // console.log('Print Back of cards: ' + RTFCast(DocCast(this.dataDoc[this.fieldKey + '_1']).text)?.Text);
-
-        // const perchance = StrCast(this.childDocs[0].text);
-
-
-
-        // const pdf = (StrCast(this.myChildLayoutPairs[0].layout.text)); //pdf
-        const queryText = this.myChildLayoutPairs[0].layout.type; //everything else
-
-        // const queryText = RTFCast(DocCast(this.dataDoc[this.fieldKey + '_1']).text)?.Text;
-
-        console.log(queryText ?? "sad")
+    @action toggleButton(childPairIndex: number, buttonID: number, isChat = false, doc?: Doc) {
+        if (!isChat) {
+            this.customGroupDictionary[NumCast(this._props.Document.customSortNumber)].set(childPairIndex, buttonID);
+            this._props.Document.customHashMap = this.mapToField;
+        }
+    
+        if (isChat && doc) {
+            this.gptGroups.set(doc, buttonID);
+        }
+    
+        // console.log(`Toggled button for childPairIndex: ${childPairIndex}, buttonID: ${buttonID}, isChat: ${isChat}`);
+        // console.log(`Updated customGroupDictionary:`, this.customGroupDictionary);
+        if (isChat && doc) {
+            console.log(`Updated gptGroups for doc ${doc}:`, this.gptGroups.get(doc));
+        }
     }
+    
 
     async childPairStringList(): Promise<string> {
         let string = "";
@@ -598,20 +624,25 @@ export class CollectionCardView extends CollectionSubView() {
     textToDoc = new Map<string, Doc>()
     gptProccessedImages = new Set<Doc>()
 
-    @action async getImageDesc(image: Doc){
-            let href = (image['data'] as URLField).url.href;
-            let hrefParts = href.split('.');
-            let hrefComplete = `${hrefParts[0]}_o.${hrefParts[1]}`;
-            try {
-                let hrefBase64 = await this.imageUrlToBase64(hrefComplete);
-                let response = await gptImageLabel(hrefBase64);
-                this.textToDoc.set(response.trim(), image);
-                this.gptProccessedImages.add(image);
-                console.log(response);
-                return response; // Return the response from gptImageLabel
-            } catch (error) {
-                console.log("bad things have happened");
-            }
+    @action async getImageDesc(image: Doc) {
+        if (this.gptProccessedImages.has(image)) {
+            // Return the already processed description
+            return Array.from(this.textToDoc.keys()).find(key => this.textToDoc.get(key) === image) || '';
+        }
+    
+        let href = (image['data'] as URLField).url.href;
+        let hrefParts = href.split('.');
+        let hrefComplete = `${hrefParts[0]}_o.${hrefParts[1]}`;
+        try {
+            let hrefBase64 = await this.imageUrlToBase64(hrefComplete);
+            let response = await gptImageLabel(hrefBase64);
+            this.textToDoc.set(response.trim(), image);
+            this.gptProccessedImages.add(image);
+            console.log(response);
+            return response; // Return the response from gptImageLabel
+        } catch (error) {
+            console.log("bad things have happened");
+        }
     }
 
    
@@ -620,41 +651,43 @@ export class CollectionCardView extends CollectionSubView() {
     //a map from the text to the Doc (for everything)
     
 
-    @action async smartSort() {
-        this.isLoading = true;
-        console.log("loading");
+    // @action async smartSort() {
+    //     this.isLoading = true;
+    //     console.log("loading");
         
-        // Store the result of childPairStringList in a variable
-        const childPairStrings = await this.childPairStringList();
+    //     // Store the result of childPairStringList in a variable
+    //     const childPairStrings = await this.childPairStringList();
         
-        if (childPairStrings === "") {
-            console.log("no child pairs :(");
-        } else {
-            console.log(childPairStrings + " og list");
-            let prompt = childPairStrings;
+    //     if (childPairStrings === "") {
+    //         console.log("no child pairs :(");
+    //     } else {
+    //         console.log(childPairStrings + " og list");
+    //         let prompt = childPairStrings;
         
-            let res = await gptAPICall(prompt, GPTCallType.SORT);
-            this.isLoading = false;
-            if (res == 'Error connecting with API.') {
-                // If GPT call failed
-                console.error('GPT call failed');
-            } else if (res != null) {
-                console.log(res);
-                this.processGptOutput(res);
-                // Update the observable with the sorted documents
-                this.sortedDocs = this.sort(this.myChildLayoutPairs, 'gpt', BoolCast(this.layoutDoc.sortDesc)).docs;
-            }
-            this.isLoading = false;
-        }
-    }
+    //         let res = await gptAPICall(prompt, GPTCallType.SORT);
+    //         this.isLoading = false;
+    //         if (res == 'Error connecting with API.') {
+    //             // If GPT call failed
+    //             console.error('GPT call failed');
+    //         } else if (res != null) {
+    //             console.log(res);
+    //             this.processGptOutput(res);
+    //             // Update the observable with the sorted documents
+    //             this.sortedDocs = this.sort(this.myChildLayoutPairs, 'gpt', BoolCast(this.layoutDoc.sortDesc)).docs;
+    //         }
+    //         this.isLoading = false;
+    //     }
+    // }
 
-    gptGroups = new Map<Doc, number>
+    gptGroups = new ObservableMap<Doc, number>
+    @observable amGPTGroups = 0
 
      // Method to convert the GPT-produced string into a map
     processGptOutput(gptOutput: string) {
 
         // Split the string into individual list items
         const listItems = gptOutput.split('======').filter(item => item.trim() !== '');
+        this.amGPTGroups = listItems.length
 
         listItems.forEach((item, index) => {
             // Split the item by '~~~~~~' to get all descriptors
@@ -678,14 +711,15 @@ export class CollectionCardView extends CollectionSubView() {
     @observable isChatPopupOpen = false;
 
     @action openChatPopup = async () => {
-    this.isChatPopupOpen = true;
-    GPTPopup.Instance.setVisible(true);
-    GPTPopup.Instance.setMode(GPTPopupMode.SORT);
-    
-    // Await the promise to get the string result
-    const sortDesc = await this.childPairStringList();
-    GPTPopup.Instance.setSortDesc(sortDesc);
-    GPTPopup.Instance.onSortComplete = this.handleGptSortResult;
+        this.isChatPopupOpen = true;
+        GPTPopup.Instance.setVisible(true);
+        GPTPopup.Instance.setMode(GPTPopupMode.SORT);
+        
+        // Await the promise to get the string result
+        const sortDesc = await this.childPairStringList();
+        GPTPopup.Instance.setCardsDoneLoading(true); // Set dataDoneLoading to true after data is loaded
+        GPTPopup.Instance.setSortDesc(sortDesc);
+        GPTPopup.Instance.onSortComplete = this.handleGptSortResult;
 };
     @action handleGptSortResult = (sortResult: string) => {
         this.processGptOutput(sortResult);
@@ -696,19 +730,34 @@ export class CollectionCardView extends CollectionSubView() {
 
     
 
-    renderButtons(childPairIndex: number) {
+    renderButtons(childPairIndex: number, doc?: Doc, isChat = false) {
         const buttons = []; // Array to hold the button elements
-
-        let amButtons = 4;
-
-        let activeButtonIndex = this.customGroupDictionary[NumCast(this._props.Document.customSortNumber)].get(childPairIndex);
-
+        const groupNumber = NumCast(this._props.Document.customSortNumber);
+    
+        let amButtons = 4; // Adjusted to your context
+        let activeButtonIndex = this.customGroupDictionary[groupNumber].get(childPairIndex);
+    
+        if (isChat && doc) {
+            if (this.amGPTGroups > 4){
+                amButtons = this.amGPTGroups;
+            }
+            activeButtonIndex = this.gptGroups.get(doc);
+        }
+    
+        console.log("childPairIndex:", childPairIndex, "activeButtonIndex:", activeButtonIndex, "groupNumber:", groupNumber);
+    
         for (let i = 0; i < amButtons; i++) {
-            const isActive = activeButtonIndex == i;
-
-            buttons.push(<button key={i} style={{ backgroundColor: `${isActive ? '#4476f7' : '#323232'}` }} onClick={() => this.toggleButton(childPairIndex, i)}></button>);
+            const isActive = activeButtonIndex === i;
+            console.log(`Rendering button ${i} for childPairIndex ${childPairIndex} isActive: ${isActive}`);
+            buttons.push(
+                <button
+                    key={i}
+                    style={{ backgroundColor: isActive ? '#4476f7' : '#323232' }}
+                    onClick={() => this.toggleButton(childPairIndex, i, isChat, doc)}
+                ></button>
+            );
         }
-
+    
         const totalWidth = amButtons * 35 + amButtons * 2 * 5 + 6;
         return (
             <div className="card-button-container" style={{ width: `${totalWidth}px` }}>
-- 
cgit v1.2.3-70-g09d2

