|
1 |
| -import { useSession, useSupabaseClient } from "@supabase/auth-helpers-react" |
2 |
| -import React, { useEffect, useState } from "react" |
| 1 | +import React, { useEffect, useState } from "react"; |
| 2 | +import { useSession, useSupabaseClient } from "@supabase/auth-helpers-react"; |
3 | 3 | import { ViewRovers } from "../Automatons/BuildRover";
|
4 | 4 |
|
5 | 5 | export default function CollectItemFromSector() {
|
6 | 6 | const supabase = useSupabaseClient();
|
7 | 7 | const session = useSession();
|
| 8 | + const user = session?.user?.id; |
8 | 9 |
|
9 | 10 | const [userSectors, setUserSectors] = useState<any[]>([]);
|
10 | 11 | const [selectedSectorId, setSelectedSectorId] = useState<string>('');
|
11 |
| - const [timeOfDeploy, setTimeOfDeploy] = useState<Date | null>(null); |
12 |
| - const [isDeployed, setIsDeployed] = useState<boolean>(false); |
| 12 | + const [deployedRover, setDeployedRover] = useState<any>(null); |
13 | 13 | const [reward, setReward] = useState<number>(0);
|
14 | 14 |
|
15 | 15 | useEffect(() => {
|
16 |
| - fetchUserSectors(); |
| 16 | + if (user) { |
| 17 | + fetchUserSectors(user); |
| 18 | + checkDeployedRover(user); |
| 19 | + const storedDeployedRover = localStorage.getItem("deployedRover"); |
| 20 | + if (storedDeployedRover) { |
| 21 | + setDeployedRover(JSON.parse(storedDeployedRover)); |
| 22 | + } |
| 23 | + } |
17 | 24 | }, [session]);
|
18 | 25 |
|
19 |
| - const fetchUserSectors = async () => { |
| 26 | + useEffect(() => { |
| 27 | + if (deployedRover) { |
| 28 | + localStorage.setItem("deployedRover", JSON.stringify(deployedRover)); |
| 29 | + } else { |
| 30 | + localStorage.removeItem("deployedRover"); |
| 31 | + } |
| 32 | + }, [deployedRover]); |
| 33 | + |
| 34 | + const fetchUserSectors = async (userId: string) => { |
20 | 35 | try {
|
21 | 36 | const { data, error } = await supabase
|
22 | 37 | .from("basePlanetSectors")
|
23 | 38 | .select("*")
|
24 |
| - .eq("owner", session?.user?.id); |
25 |
| - |
| 39 | + .eq("owner", userId); |
| 40 | + |
26 | 41 | if (error) {
|
27 | 42 | throw error;
|
28 | 43 | }
|
29 |
| - |
| 44 | + |
30 | 45 | if (data) {
|
31 | 46 | setUserSectors(data);
|
32 | 47 | }
|
33 | 48 | } catch (error) {
|
34 | 49 | console.error("Error fetching user sectors:", error.message);
|
35 | 50 | }
|
36 | 51 | };
|
37 |
| - |
| 52 | + |
| 53 | + const checkDeployedRover = async (userId: string) => { |
| 54 | + try { |
| 55 | + const { data, error } = await supabase |
| 56 | + .from("inventoryUSERS") |
| 57 | + .select("*") |
| 58 | + .eq("owner", userId); |
| 59 | + |
| 60 | + if (error) { |
| 61 | + throw error; |
| 62 | + } |
| 63 | + |
| 64 | + if (data && data.length > 0) { |
| 65 | + setDeployedRover(data[0]); // Assuming only one rover is deployed at a time |
| 66 | + } |
| 67 | + } catch (error) { |
| 68 | + console.error("Error checking deployed rover:", error.message); |
| 69 | + } |
| 70 | + }; |
| 71 | + |
38 | 72 | const handleSectorSelect = (sectorId: string) => {
|
39 | 73 | setSelectedSectorId(sectorId);
|
40 | 74 | };
|
41 | 75 |
|
| 76 | + const calculateReward = () => { |
| 77 | + if (deployedRover && deployedRover.time_of_deploy) { |
| 78 | + const currentTime = new Date(); |
| 79 | + const timeDifference = currentTime.getTime() - new Date(deployedRover.time_of_deploy).getTime(); |
| 80 | + const secondsDeployed = Math.floor(timeDifference / 1000); // Convert milliseconds to seconds |
| 81 | + |
| 82 | + // Calculate reward every 10 seconds, with a maximum of 20 items |
| 83 | + const rewardItems = Math.min(Math.floor(secondsDeployed / 10), 20); |
| 84 | + setReward(rewardItems); |
| 85 | + } |
| 86 | + }; |
| 87 | + |
42 | 88 | const deployRover = async () => {
|
43 | 89 | if (!selectedSectorId) {
|
44 | 90 | console.error("Please select a sector before deploying a rover.");
|
45 | 91 | return;
|
46 | 92 | }
|
47 |
| - |
48 |
| - // Check if the user owns the selected sector |
49 |
| - const ownedSector = userSectors.find(sector => sector.id === selectedSectorId); |
50 |
| - if (!ownedSector) { |
51 |
| - console.error("You don't own the selected sector."); |
52 |
| - return; |
53 |
| - }; |
54 |
| - |
| 93 | + |
55 | 94 | try {
|
56 |
| - // Update inventoryUSERS table |
57 |
| - const { data, error } = await supabase |
| 95 | + // Retrieve the user's items |
| 96 | + const { data: userData, error: userError } = await supabase |
| 97 | + .from("inventoryUSERS") |
| 98 | + .select("*") |
| 99 | + .eq("owner", session?.user?.id); |
| 100 | + |
| 101 | + if (userError) { |
| 102 | + throw userError; |
| 103 | + } |
| 104 | + |
| 105 | + // Find the rover with notes "first rover created by user" |
| 106 | + const roverToDeploy = userData.find(item => item.notes === "first rover created by user"); |
| 107 | + |
| 108 | + if (!roverToDeploy) { |
| 109 | + console.error("No rover available for deployment."); |
| 110 | + return; |
| 111 | + } |
| 112 | + |
| 113 | + // Update the rover's planetSector and time_of_deploy |
| 114 | + const { error } = await supabase |
58 | 115 | .from("inventoryUSERS")
|
59 | 116 | .update({
|
60 | 117 | planetSector: selectedSectorId,
|
61 | 118 | time_of_deploy: new Date().toISOString()
|
62 | 119 | })
|
63 |
| - .eq("owner", session?.user?.id); |
64 |
| - |
| 120 | + .eq("owner", session?.user?.id) |
| 121 | + .eq("id", roverToDeploy.id); |
| 122 | + |
65 | 123 | if (error) {
|
66 | 124 | throw error;
|
67 | 125 | }
|
68 |
| - |
69 |
| - // Set deployment status |
70 |
| - setTimeOfDeploy(new Date()); |
71 |
| - setIsDeployed(true); |
| 126 | + |
| 127 | + setDeployedRover({ |
| 128 | + ...roverToDeploy, |
| 129 | + planetSector: selectedSectorId, |
| 130 | + time_of_deploy: new Date().toISOString() |
| 131 | + }); |
| 132 | + |
| 133 | + console.log("Rover deployed successfully."); |
72 | 134 | } catch (error) {
|
73 | 135 | console.error("Error deploying rover:", error.message);
|
74 |
| - }; |
75 |
| - |
76 |
| - // Update this so that it can pull already deployed rovers |
77 |
| - }; |
78 |
| - |
79 |
| - const calculateReward = () => { |
80 |
| - // Calculate the reward based on deployment time |
81 |
| - if (timeOfDeploy) { |
82 |
| - const currentTime = new Date(); |
83 |
| - const timeDifference = currentTime.getTime() - timeOfDeploy.getTime(); |
84 |
| - // Convert milliseconds to hours |
85 |
| - const hoursDeployed = timeDifference / (1000 * 60 ); // * 60 -> for one hour/item |
86 |
| - // For now, let's say 1 item per hour |
87 |
| - setReward(Math.min(Math.floor(hoursDeployed), 6)); |
| 136 | + } |
| 137 | + }; |
| 138 | + |
| 139 | + const collectReward = async () => { |
| 140 | + try { |
| 141 | + // Check if there is a deployed rover |
| 142 | + if (deployedRover && deployedRover.time_of_deploy) { |
| 143 | + // Fetch the sector data to determine the reward item |
| 144 | + const sectorData = await supabase |
| 145 | + .from("basePlanetSectors") |
| 146 | + .select("deposit") |
| 147 | + .eq("id", deployedRover.planetSector) |
| 148 | + .single(); |
| 149 | + |
| 150 | + if (sectorData.error) { |
| 151 | + throw sectorData.error; |
| 152 | + } |
| 153 | + |
| 154 | + const deposit = sectorData.data?.deposit; |
| 155 | + |
| 156 | + // Calculate the reward based on the deposit value |
| 157 | + const rewardItemId = deposit ? deposit : 0; |
| 158 | + |
| 159 | + // Calculate the reward based on the time deployed |
| 160 | + const currentTime = new Date(); |
| 161 | + const timeDifference = currentTime.getTime() - new Date(deployedRover.time_of_deploy).getTime(); |
| 162 | + const hoursDeployed = Math.min(Math.floor(timeDifference / (1000 * 60 * 60)), 6); // Cap at 6 hours |
| 163 | + |
| 164 | + // Create a new entry in inventoryUSERS for the reward item |
| 165 | + const { data: rewardData, error: rewardError } = await supabase |
| 166 | + .from("inventoryUSERS") |
| 167 | + .insert([ |
| 168 | + { |
| 169 | + owner: session?.user?.id, |
| 170 | + item: rewardItemId, |
| 171 | + quantity: hoursDeployed, |
| 172 | + notes: `Reward collected from rover/automaton ${deployedRover.id}` |
| 173 | + } |
| 174 | + ]); |
| 175 | + |
| 176 | + if (rewardError) { |
| 177 | + throw rewardError; |
| 178 | + } |
| 179 | + |
| 180 | + // Clear the timestamp value for the deployed rover |
| 181 | + const { error } = await supabase |
| 182 | + .from("inventoryUSERS") |
| 183 | + .update({ |
| 184 | + time_of_deploy: null |
| 185 | + }) |
| 186 | + .eq("id", deployedRover.id); |
| 187 | + |
| 188 | + if (error) { |
| 189 | + throw error; |
| 190 | + } |
| 191 | + |
| 192 | + setDeployedRover(null); |
| 193 | + console.log("Rewards collected successfully."); |
| 194 | + } else { |
| 195 | + console.error("No rewards to collect."); |
| 196 | + } |
| 197 | + } catch (error) { |
| 198 | + console.error("Error collecting rewards:", error.message); |
88 | 199 | }
|
89 | 200 | };
|
90 |
| - |
91 |
| - const collectReward = () => { |
92 |
| - // Here you can add the reward to the user's inventory |
93 |
| - // For now, let's just log the reward |
94 |
| - console.log("Collected reward:", reward); |
95 |
| - }; |
96 |
| - |
| 201 | + |
97 | 202 | return (
|
98 | 203 | <div>
|
99 | 204 | <h1>Collect Item from Sector</h1>
|
100 |
| - <h2>User Sectors</h2> |
101 |
| - <ul> |
102 |
| - {userSectors.map(sector => ( |
103 |
| - <li key={sector.id} onClick={() => handleSectorSelect(sector.id)}> |
104 |
| - {sector.id} - {sector.name} - {sector.deposit} |
105 |
| - </li> |
106 |
| - ))} |
107 |
| - </ul> |
108 |
| - <h2>Selected Sector</h2> |
109 |
| - {selectedSectorId && ( |
110 |
| - <div> |
111 |
| - <p>ID: {selectedSectorId}</p> |
112 |
| - {/* Display other sector details if needed */} |
113 |
| - </div> |
114 |
| - )} |
115 |
| - <h2>Deploy Rover</h2> |
116 |
| - <button onClick={deployRover}>Deploy Rover</button> |
117 |
| - <h2>Reward</h2> |
118 |
| - {isDeployed && ( |
119 |
| - <div> |
120 |
| - <p>Reward: {reward}</p> |
121 |
| - <button onClick={calculateReward}>Calculate Reward</button> |
122 |
| - <button onClick={collectReward}>Collect Reward</button> |
| 205 | + <div style={{ border: "1px solid black", padding: "10px", marginBottom: "20px" }}> |
| 206 | + <h2>User Sectors</h2> |
| 207 | + <ul> |
| 208 | + {userSectors.map(sector => ( |
| 209 | + <li key={sector.id} onClick={() => handleSectorSelect(sector.id)}> |
| 210 | + Sector name: {sector.id} - {sector.name} - {sector.deposit} |
| 211 | + </li> |
| 212 | + ))} |
| 213 | + </ul> |
| 214 | + </div> |
| 215 | + <div style={{ border: "1px solid black", padding: "10px", marginBottom: "20px" }}> |
| 216 | + <h2>Selected Sector</h2> |
| 217 | + {selectedSectorId && ( |
| 218 | + <div> |
| 219 | + <p>ID: {selectedSectorId}</p> |
| 220 | + </div> |
| 221 | + )} |
| 222 | + </div> |
| 223 | + <div style={{ border: "1px solid black", padding: "10px", marginBottom: "20px" }}> |
| 224 | + <h2>Deploy Rover</h2> |
| 225 | + <button style={{ padding: "10px", marginRight: "10px" }} onClick={deployRover}>Deploy Rover</button> |
| 226 | + </div> |
| 227 | + {/* Reward section */} |
| 228 | + {deployedRover && deployedRover.time_of_deploy && ( |
| 229 | + <div style={{ border: "1px solid black", padding: "10px", marginBottom: "20px" }}> |
| 230 | + <h2>Reward</h2> |
| 231 | + <div> |
| 232 | + <p>Reward: {reward}</p> |
| 233 | + <button style={{ padding: "10px", marginRight: "10px" }} onClick={calculateReward}>Calculate Reward</button> |
| 234 | + <button style={{ padding: "10px" }} onClick={collectReward}>Collect Reward</button> |
| 235 | + </div> |
123 | 236 | </div>
|
124 | 237 | )}
|
| 238 | + <h2>Deployed Rovers</h2> |
| 239 | + <ViewRovers /> |
125 | 240 | </div>
|
126 |
| - ); |
| 241 | + ); |
127 | 242 | }
|
0 commit comments